如何设置一个HttpClient的请求Content-Type头? [英] How do you set the Content-Type header for an HttpClient request?

查看:16341
本文介绍了如何设置一个HttpClient的请求Content-Type头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想所要求的一个API我设置一个的HttpClient 对象的内容类型头我打电话。

I'm trying to set the Content-Type header of an HttpClient object as required by an API I am calling.

我尝试设置内容类型象下面这样:

I tried setting the Content-Type like below:

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");
    // ...
}

这使我可以添加接受头,但是当我尝试添加内容类型它抛出以下例外:

It allows me to add the Accept header but when I try to add Content-Type it throws the following exception:

误用头名。确保请求头与使用
  的Htt prequestMessage ,响应头与的Htt presponseMessage ,和
  内容头部与 HttpContent 的对象。

Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

如何设置在的HttpClient 要求内容类型头?

推荐答案

内容类型是内容的标题,而不是要求,这就是为什么这种失败的。 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);
      });

这篇关于如何设置一个HttpClient的请求Content-Type头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆