从其他服务器请求访问令牌时遇到一些困难。
获得该请求的请求是:
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;
}
当我尝试获取请求流时,我得到了这个execption:Unable to connect to the remote server
答案 0 :(得分:1)
检查一下......
它不是02
O2
在您的代码中,可能是错误
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create("http://api.amazon.com/auth/**02**/token");
试试这个
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create("https://api.amazon.com/auth/o2/token");
谢谢......
答案 1 :(得分: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...
}