我正在尝试使用HttpClient.PostAsync调用API,并且收到错误请求。我检查了Fiddler,发现正文请求正在编码,并且Transfer-Encoding:在标题中分块。
response = Client.PostAsync(url, toSend, mediaTypeFormatter).Result;
toSend
是一类
[DataContract]
public class OAuthRequestBody
{
[DataMember(Name = "grant_type")]
public string GrantType { get; set; }
[DataMember(Name = "tpl")]
public string Tpl { get; set; }
[DataMember(Name = "user_login_id")]
public string UserLogin { get; set; }
}
在这种情况下,Mediaformatter
是Json,但可以有所不同,这就是为什么我们不使用JsonFormatter
。
当我在Fiddler中检查textView时,会看到以下内容:
66
{"grant_type":"client_credentials","tpl":"{number}","user_login_id":"x"}
0
我不知道66和0的来源。
The Raw Headers:
POST http://example.com/token
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json; charset=utf-8
Accept: application/json
Accept-Encoding: gzip, deflate
Authorization: Basic FancyLongBase64
Host: example.com
66
{"grant_type":"client_credentials","tpl":"{number}","user_login_id":"x"}
0
我尝试了多种方法,但是编码似乎始终存在。也许有一些配置。
构建请求:
var body = new OAuthRequestBody
{
GrantType = "client_credentials",
Tpl = Tpl,
UserLogin = "1"
};
mediaTypeFormatter = new JsonMediaTypeFormatter();
url = "/token" //Not the actual path but same idea