c# - 这个 RestClient JSON POST 的等效 HttpClient JSON POST 是什么?

标签 c# .net http dotnet-httpclient

给定:

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/

相关文章:

c# - 将控件拖放到自定义用户控件上会隐藏

c# - 有没有一种简单的方法可以打开 Uri 并获取它指向的任何内容? (C#)

c# - WaitHandle.WaitAny 每次调用时都会分配 WaitHandle[] 的副本

c# - 异常和返回语句是 C# 中唯一可能的提前退出吗?

c# - ASP.NET MVC 和 C# : HttpStatusCodeResult() vs HttpNotFound()

c# - MongoDB 事务

c# - 通过属性名称以及 JsonProperty 将 JSON 反序列化为对象

.net 和多核

angular - http拦截器不添加带有字符串标记 Angular header

javascript - Angular js 不等待 $http 吗?