昨天申请的第三方客户端API通过了,今天上手开发,结果第一步就卡住了。。。
我先用博客园发给我的 ClientId 和 ClientSecret 去做 Client_Credentials授权 的测试,博客园提供的 apizza 和 postman 测试能通过,但是我写的代码测试过不了,均返回400错误,目测应该是json格式哪里错了?
下面贴下json数据模型的代码
public class CredentialsRequest
{
[JsonProperty("client_id")]
public string ClientID { get; set; }
[JsonProperty("client_secret")]
public string ClientSecret { get; set; }
[JsonProperty("grant_type")]
public string GrantType { get; set; }
public CredentialsRequest()
{
GrantType = "client_credentials";
}
}
http请求的代码:
public static WebRequest CreatePostRequest(string url)
{
// 参数检查
Prediction.IsTrue(string.IsNullOrEmpty(url), "url can not be null or empty");
var request = WebRequest.Create(url);
request.Method = "POST";
return request;
}
private static void WriteRequestBody(WebRequest request , object model)
{
// 参数检查
Prediction.IsTrue(request == null, "request can not be null");
Prediction.IsTrue(model == null, "model can not be null");
var json = JsonConvert.SerializeObject(model);
var data = Encoding.ASCII.GetBytes(json);
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
public static HttpWebRequest CreateAutnenticationRequest()
{
var request = CreatePostRequest(AuthenticationUrl) as HttpWebRequest;
request.ContentType = "application/x-www-form-urlencoded";
var model = new Net.Model.CredentialsRequest
{
ClientID = "不给看",
ClientSecret = "不给看"
};
WriteRequestBody(request, model);
return request;
}
最外层就是调用 CreateAutnenticationRequest() 这个方法然后获取 Response
有哪位麻烦给看看是哪边的参数错了吗?
搞定了,崩溃,原来这个是表单格式的数据,不是json的