发送httprequest以便接收一些数据
本文关键字:数据 httprequest 发送 | 更新日期: 2023-09-27 18:24:20
我在从其他服务器请求访问令牌时遇到了一些困难。
一个请求是:
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
检查此。。。
它不是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");
谢谢
第一个问题是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...
}