2

我在从其他服务器请求访问令牌时遇到了一些困难。

得到它的请求是:

  POST /auth/O2/token HTTP/1.1
  Host: api.amazon.com
  Content-Type: application/x-www-form-urlencoded;charset=UTF-8

  grant_type=client_credentials&scope=messaging:push&client_id=(YOUR_CLIENT_ID)&client_secret=(YOUR_CLIENT_SECRET)

我想得到的回应是:

X-Amzn-RequestId: d917ceac-2245-11e2-a270-0bc161cb589d
Content-Type: application/json

{
  "access_token":"Atc|MQEWYJxEnP3I1ND03ZzbY_NxQkA7Kn7Aioev_OfMRcyVQ4NxGzJMEaKJ8f0lSOiV-yW270o6fnkI",
  "expires_in":3600,
  "scope":"messaging:push",
  "token_type":"Bearer"
 }

我试图通过它:

private String getAccessToken(String client_id,String client_secret)
    {

            HttpWebRequest httpWReq =
            (HttpWebRequest)WebRequest.Create("http://api.amazon.com/auth/02/token");

            Encoding encoding = new UTF8Encoding();
            string postData = "grant_type=client_credentials";
            postData += "&scope=messaging:push";
            postData += "&client_id=" + client_id;
            postData += "&client_secret=" + client_secret;
            byte[] data = encoding.GetBytes(postData);

            httpWReq.Method = "POST";
            httpWReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            httpWReq.ContentLength = data.Length;

            using (Stream stream = httpWReq.GetRequestStream())  // ***here I get this exception : Unable to connect to the remote server !!!****
            {
                stream.Write(data, 0, data.Length);
            }

            HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            String jsonresponse = "";
            String temp = null;
            while ((temp = reader.ReadLine()) != null)
            {
                jsonresponse += temp;
            }

            var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(jsonresponse);
            access_token = dict["access_token"];
            String expires_in = dict["expires_in"];

        }

        return access_token;
    }

Unable to connect to the remote server当我尝试获取请求流时,我得到了这个 execption

4

2 回答 2

1

检查这个...

它不是02O2

在您的代码中,可能是错误

HttpWebRequest httpWReq =
            (HttpWebRequest)WebRequest.Create("http://api.amazon.com/auth/**02**/token");

尝试这个

              HttpWebRequest httpWReq =
    (HttpWebRequest)WebRequest.Create("https://api.amazon.com/auth/o2/token");

谢谢 ...

于 2013-07-23T13:31:26.020 回答
0

第一个问题是 api.amazon.com/auth/02/token 在端口 80 上没有任何监听(所以它不起作用);所以可能它需要https(但如果您提供参考记录在哪里,我们可以更好地建议)

其次,我认为将代码的第一部分替换为以下内容会更干净;

 using (WebClient client = new WebClient())
   {
       byte[] response = client.UploadValues("https://api.amazon.com/auth/02/token", new NameValueCollection()
       {
           { "scope", "messaging:push" },
           { "client_id", "1123" },
           { "client_secret", "2233"}
       });
       // handle response... 
   }
于 2013-07-23T13:23:20.623 回答