且构网

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

如何设置一个HttpClient的请求Content-Type头?

更新时间:2021-11-14 15:58:05

内容类型是内容的标题,而不是要求,这就是为什么这种失败的。 AddWithoutValidation 由罗伯特·利维认为可以工作,但你也可以使用创建请求内容本身时所设置的内容类型:

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 use set the content type when creating the request content itself:

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

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

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