给定:
Uri location = ...; // Remote 3rd party HTTP Rest API
string body = "SOME JSON";
以下 RestClient
代码生成服务器接受的 HTTP 流量。
var client = new RestClient(location);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json; charset=utf-8");
request.AddParameter("application/json; charset=utf-8", body,
ParameterType.RequestBody);
var restResponse = client.Execute(request);
但是,下面的 HttpClient
代码必须生成不同的 HTTP 流量(由服务器拒绝请求表示)。
using (var client = new HttpClient())
{
var request = new HttpRequestMessage();
request.Method = HttpMethod.Post;
request.RequestUri = location;
var bodyContent = new StringContent(body, Encoding.UTF8, "application/json");
request.Content = bodyContent;
request.Headers.Add("cache-control", "no-cache");
client.Timeout = TimeSpan.FromMinutes(5.0);
var response = await client.SendAsync(request);
}
为什么 HttpClient 代码序列化不同?
最佳答案
找到精确差异的一种简单方法是运行 Fiddler 或其他调试代理并检查原始请求。这是我使用 HttpClient 得到的结果:
POST http://example.com/ HTTP/1.1
cache-control: no-cache
Content-Type: application/json; charset=utf-8
Host: example.com
Content-Length: 4
Expect: 100-continue
Connection: Keep-Alive
test
还有 RestSharp:
POST http://example.com/ HTTP/1.1
cache-control: no-cache
Content-Type: application/json; charset=utf-8
Accept: application/json, text/json, text/x-json, text/javascript, application/xml, text/xml
User-Agent: RestSharp/106.6.9.0
Host: example.com
Content-Length: 4
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
test
您的结果可能因您的系统配置、版本等不同而有所不同,因此您应该自己尝试以确保。
关于c# - 这个 RestClient JSON POST 的等效 HttpClient JSON POST 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56469046/