如何为 HttpClient 请求设置 Content-Type 标头? [英] How do you set the Content-Type header for an HttpClient request?
问题描述
我正在尝试根据我正在调用的 API 的要求设置 HttpClient
对象的 Content-Type
标头.
I'm trying to set the Content-Type
header of an HttpClient
object as required by an API I am calling.
我尝试设置 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
时,它会引发以下异常:
It allows me to add the Accept
header but when I try to add Content-Type
it throws the following exception:
误用的标头名称.确保请求标头与HttpRequestMessage
,带有 HttpResponseMessage
的响应头,以及带有 HttpContent
对象的内容标头.
Misused header name. Make sure request headers are used with
HttpRequestMessage
, response headers withHttpResponseMessage
, and content headers withHttpContent
objects.
如何在 HttpClient
请求中设置 Content-Type
标头?
How can I set the Content-Type
header in a HttpClient
request?
推荐答案
内容类型是内容的标头,而不是请求的标头,这就是失败的原因.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);
});
这篇关于如何为 HttpClient 请求设置 Content-Type 标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!