且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为 HttpClient 请求设置 Content-Type 标头?

更新时间:2021-12-02 21:30:32

内容类型是内容的标头,而不是请求的标头,这就是失败的原因.AddWithoutValidation 按照 Robert Levy 的建议 可能有效,但您也可以在创建时设置内容类型请求内容本身(请注意,代码片段在两个地方添加了 application/json - 用于 Accept 和 Content-Type 标头):

The content type is a header of the content, not of the request, which is why this is failing. AddWithoutValidation as suggested by Robert Levy may work, but you can also set the content type when creating the request content itself (note that the code snippet adds application/json in two places-for Accept and Content-Type headers):

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://example.com/");
client.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{"name":"John Doe","age":33}",
                                    Encoding.UTF8, 
                                    "application/json");//CONTENT-TYPE header

client.SendAsync(request)
      .ContinueWith(responseTask =>
      {
          Console.WriteLine("Response: {0}", responseTask.Result);
      });