与此 RestClient JSON POST 等效的 HttpClient JSON POST 是什么?

What is the equivalent HttpClient JSON POST to this RestClient JSON POST?

鉴于:

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

您的结果可能会因您的系统配置、版本等不同而有所不同,因此请您自行尝试确定。