2015-06-16 94 views
3

我無法通過C#控制檯(桌面)應用程序調用Yahoo Gemini API來訪問Yahoo Gemini廣告。Oauth2 Yahoo Gemini API

下面是步驟我用:

  1. 創建於https://developer.yahoo.com/apps/create/安裝的應用程序。這給了我{Client ID}{Client Secret}
  2. https://api.login.yahoo.com/oauth2/request_auth?client_id={Client ID} &redirect_uri=oob&response_type=code&language=en-us。這會將我帶到我登錄的yahoo登錄屏幕。按「同意」按鈕,下一個屏幕顯示七字母​​授權碼(例如nzbcns9)。我寫下這個授權碼。
  3. 然後我用下面的代碼,試圖獲得訪問令牌:

    class Program 
    { 
    static void Main(string[] args) 
    { 
        string clientId = {Client ID}; 
        string secret = {Client Secret}; 
    
        var request = WebRequest.Create(@"https://api.login.yahoo.com/oauth2/get_token"); 
        request.Method = "POST"; 
    
        SetBasicAuthHeader(request, clientId, secret); 
    
        string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9"; 
        ASCIIEncoding encoding = new ASCIIEncoding(); 
        byte[] byte1 = encoding.GetBytes(postData); 
        request.ContentLength = byte1.Length; 
        Stream dataStream = request.GetRequestStream(); 
        dataStream.Write(byte1, 0, byte1.Length); 
        dataStream.Close(); 
    
        request.ContentType = "application/x-www-form-urlencoded"; 
        var response = request.GetResponse(); 
        Console.WriteLine(((HttpWebResponse)response).StatusDescription); 
    } 
    
    static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword) 
    { 
        string authInfo = userName + ":" + userPassword; 
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); 
        request.Headers["Authorization"] = "Basic " + authInfo; 
    } 
    } 
    

然後我得到

Unhandled Exception: System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse().

我做了什麼錯?

我也嘗試發佈使用招相同的消息,我得到

{"error":"invalid_request"}

回答

1

我想你的代碼,什麼工作對我來說是放線request.ContentType = "application/x-www-form-urlencoded";Stream dataStream = request.GetRequestStream();

所以這個工作:

string postData = "grant_type=authorization_code&redirect_uri=oob&code=nzbcns9"; 
    ASCIIEncoding encoding = new ASCIIEncoding(); 
    byte[] byte1 = encoding.GetBytes(postData); 
    request.ContentLength = byte1.Length; 
    request.ContentType = "application/x-www-form-urlencoded"; 
    Stream dataStream = request.GetRequestStream(); 
    dataStream.Write(byte1, 0, byte1.Length); 
    dataStream.Close(); 
+0

這對我不起作用。 API改變了,還是我錯過了一些東西?使用上面的代碼,我得到: \t \t遠程服務器返回錯誤:(400)錯誤的請求。 – Foozinator

0

這兩種都不適合我,但是它在我改變SetBasicAuthHeader使用ISO-8859-1編碼後確實有效:

static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword) 
    { 
     string authInfo = userName + ":" + userPassword; 
     authInfo = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(authInfo)); 
     request.Headers[ "Authorization" ] = "Basic " + authInfo; 
    } 
+0

請注意,這將爲您提供刷新令牌。驗證碼將在每次使用後過期,因此請保存刷新令牌並將其用作應用程序的起點。 – Foozinator