프로그래밍/.NET2013. 1. 18. 16:46

밑에 소스는 Google Oauth 2.0 인증과 관련해서 RefeshToken 값을 이용해 AccessToken 값을 구하는 구글 API입니다.

"####################################" 이 들어간 문자는 중요한 값이라 일부러 숨겼습니다.

"대충 이런식으로 쓴다" 정도로 봐주시면 감사하겠습니다.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Http_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            // 요청을 보내는 URI
            string strUri = "https://accounts.google.com/o/oauth2/token";

            // POST, GET 보낼 데이터 입력
            StringBuilder dataParams = new StringBuilder();
            dataParams.Append("client_id=#############################################");
            dataParams.Append("&client_secret=####################################");
            dataParams.Append("&refresh_token=####################################");
            dataParams.Append("&grant_type=refresh_token");

            // 요청 String -> 요청 Byte 변환
            byte[] byteDataParams = UTF8Encoding.UTF8.GetBytes(dataParams.ToString());

            /////////////////////////////////////////////////////////////////////////////////////
            /* POST */
            // HttpWebRequest 객체 생성, 설정
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUri);
            request.Method = "POST";    // 기본값 "GET"
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteDataParams.Length;

            /* GET */
            // GET 방식은 Uri 뒤에 보낼 데이터를 입력하시면 됩니다.
            /*
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUri + "?" + dataParams);
            request.Method = "GET";
            */
            //////////////////////////////////////////////////////////////////////////////////////
            

            // 요청 Byte -> 요청 Stream 변환
            Stream stDataParams = request.GetRequestStream();
            stDataParams.Write(byteDataParams, 0, byteDataParams.Length);
            stDataParams.Close();

            // 요청, 응답 받기
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            
            // 응답 Stream 읽기
            Stream stReadData = response.GetResponseStream();
            StreamReader srReadData = new StreamReader(stReadData, Encoding.Default);

            // 응답 Stream -> 응답 String 변환
            string strResult = srReadData.ReadToEnd();

            Console.WriteLine(strResult);
            Console.ReadLine();
        }
    }
}



Posted by 건깡