【问题标题】:What is the equivalent HttpClient JSON POST to this RestClient JSON POST?这个 RestClient JSON POST 的等效 HttpClient JSON POST 是什么?
【发布时间】:2019-06-06 21:14:53
【问题描述】:

给定:

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 代码的序列化方式不同?

【问题讨论】:

  • 当您说服务器拒绝它时需要更多详细信息。状态码、正文等您是否拥有服务器?它是否在寻找特定的标题?您是否尝试过启动本地 api 以查看如何接收请求?
  • 感谢您的反馈和支持。我重申了这个问题,以强调我正在尝试复制 RestClient 所表现出的行为(不一定要尝试获得工作的客户端/服务器 API)。

标签: c# .net http dotnet-httpclient


【解决方案1】:

找到精确差异的一种简单方法是运行 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

您的结果可能会因您的系统配置、版本等而有所不同,因此您应该自己尝试以确保。

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 2015-06-10
    • 2016-03-07
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多