我正在使用Verizon ThingSpace api,在这里找到。
我正在尝试生成Oauth令牌。API文档提供了一个curl示例:
curl -X POST -d "grant_type=client_credentials" -H "Authorization: Basic BASE64_ENCODED_APP_KEY_AND_SECRET" -H "Content-Type: application/x-www-form-urlencoded" "/api/ts/v1/oauth2/token"
我已经能够在c#中使用旧的HTTPWebRequest成功复制curl命令,但是使用新的HttpClient失败了。
我得到的返回值是:{"error":"invalid_request","error_description":"Invalid grant_type parameter or parameter missing"}
在API文档中使用c#中更新的HttpClient类复制curl示例的正确方法是什么?我已经检查了这个答案,但是它没有解决我使用grant_type时遇到的问题。 编辑:
这是HTTPWebRequest实现,它按预期工作:
public static void API_Login()
{
Console.WriteLine("API Request ----------------------------------");
string url = @https://thingspace.verizon.com/api/ts/v1/oauth2/token;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("Authorization", $"Basic {encodedKeyAndSecret}");
var body = "grant_type=client_credentials";
var data = Encoding.ASCII.GetBytes(body);
httpWebRequest.ContentLength = data.Length;
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
JsonObject jsonObject = (JsonObject)JsonObject.Parse(result);
apiToken = jsonObject["access_token"].ToString();
}
}
这里是HttpClient实现,这是不正常工作:
public async static void HttpClient_API_Login(string encodedKeyAndSecret)
{
string url = @https://thingspace.verizon.com/api/ts/v1/oauth2/token;
var client = new HttpClient();
var body = "grant_type=client_credentials";
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Headers =
{
{ HttpRequestHeader.ContentType.ToString(), $"application/x-www-form-urlencoded" },
{ HttpRequestHeader.Authorization.ToString(), $"Basic {encodedKeyAndSecret}" },
},
Content = new StringContent(body)
};
var response = client.SendAsync(request).Result;
var sr = await response.Content.ReadAsStringAsync();
Console.WriteLine("response: " + sr);
}
我已经通过更改代码解决了这个问题,如下所示:
public async static void HttpClient_API_Login(string encodedKeyAndSecret)
{
string url = @https://thingspace.verizon.com/api/ts/v1/oauth2/token;
var client = new HttpClient();
var formData = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var request = new HttpRequestMessage()
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Headers =
{
{ HttpRequestHeader.ContentType.ToString(), $"application/x-www-form-urlencoded" },
{ HttpRequestHeader.Authorization.ToString(), $"Basic {encodedKeyAndSecret}" },
},
Content = new FormUrlEncodedContent(body)
};
问题是正文是字符串内容,而不是表单内容。