小编典典

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

c#

我正在尝试根据我要调用的API 设置对象的Content-Type标头HttpClient

我尝试设置Content-Type如下:

using (var httpClient = new HttpClient())
{
    httpClient.BaseAddress = new Uri("http://example.com/");
    httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
    httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
    // ...
}

它允许我添加Accept标题,但是当我尝试添加Content-Type它时,抛出以下异常:

标头名称滥用。确保请求标HttpRequestMessage头与一起使用
,响应标头与一起使用HttpResponseMessage,内容标头与HttpContent对象一起使用。

如何Content-TypeHttpClient请求中设置标题?


阅读 1659

收藏
2020-05-19

共1个答案

小编典典

内容类型是内容的标头,而不是请求的标头,这就是失败的原因。AddWithoutValidation如Robert
Levy所建议的那样可能有效,但是您也可以在创建请求内容本身时设置内容类型(请注意,代码段在两个位置为“ Accept”和“ Content-
Type”标头添加了“ application / json”):

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);
      });
2020-05-19