Oauth2 Yahoo Gemini API

时间:2015-06-16 22:37:19

标签: oauth-2.0 yahoo-api

我无法调用Yahoo Gemini API从我的C#控制台(桌面)应用程序访问Yahoo Gemini Advertising。

以下是我使用的步骤:

  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;
    }
    }
    
  4. 然后我得到

      

    未处理的异常:System.Net.WebException:远程服务器返回错误:(401)未经授权。在System.Net.HttpWebRequest.GetResponse()。

    我做错了什么?

    我也尝试使用Fiddler发布相同的消息,我得到了

      

    { “错误”: “INVALID_REQUEST”}

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

这些都不适合我,但是一旦我将SetBasicAuthHeader更改为使用ISO-8859-1编码,它确实有效:

<?php
require("config.php");
$uname =$_POST["uname"];
$pass = $_POST["pass"];
$fname = $_POST["fname"];
$lname = $_POST["lname"];

$insert=$db->prepare("insert into users (uname,pass,fname,lname) values(?,?,?,?)");
$insert->bind_param("ssss",$uname,$pass,$fname,$lname);
if($insert->execute()){
    echo "ok";
}
else
{$db->error;}

?>