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

在尝试使用HttpClient调用API并设置Content-Type标头时遇到问题。错误提示为标头名称滥用。解决方案包括使用HttpRequestMessage的Headers.ContentType属性,或者在创建请求内容时设置,如使用Flurl库可以简化这一过程。
摘要由CSDN通过智能技术生成

本文翻译自:How do you set the Content-Type header for an HttpClient request?

I'm trying to set the Content-Type header of an HttpClient object as required by an API I am calling. 我正在尝试根据我正在调用的API设置HttpClient对象的Content-Type标头。

I tried setting the Content-Type like below: 我尝试如下设置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");
    // ...
}

It allows me to add the Accept header but when I try to add Content-Type it throws the following exception: 它允许我添加Accept标头,但是当我尝试添加Content-Type它将引发以下异常:

Misused header name. 标头名称滥用。 Make sure request headers are used with HttpRequestMessage , response headers with HttpResponseMessage , and content headers with HttpContent objects. 确保HttpRequestMessage使用请求标头, HttpResponseMessage使用响应标头, HttpContent对象使用内容标头。

How can I set the Content-Type header in a HttpClient request? 如何在HttpClient请求中设置Content-Type标头?


#1楼

参考:https://stackoom.com/question/io9O/如何设置HttpClient请求的Content-Type标头


#2楼

Call AddWithoutValidation instead of Add (see this MSDN link ). 调用AddWithoutValidation而不是Add (请参阅此MSDN链接 )。

Alternatively, I'm guessing the API you are using really only requires this for POST or PUT requests (not ordinary GET requests). 另外,我猜您正在使用的API实际上仅需要POST或PUT请求(而不是普通的GET请求)。 In that case, when you call HttpClient.PostAsync and pass in an HttpContent , set this on the Headers property of that HttpContent object. 在这种情况下,当您调用HttpClient.PostAsync并传递HttpContent ,请在该HttpContent对象的Headers属性上进行设置。


#3楼

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): 由Robert Levy建议的AddWithoutValidation可能有效,但是您也可以在创建请求内容本身时设置内容类型(请注意,代码段在两个位置为“ 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);
      });

#4楼

对于那些没有看到约翰对卡洛斯解决方案发表评论的人...

req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

#5楼

If you don't mind a small library dependency, Flurl.Http [disclosure: I'm the author] makes this uber-simple. 如果您不介意小的库依赖关系, 那么Flurl.Http [公开:我是作者]使这个超级简单。 Its PostJsonAsync method takes care of both serializing the content and setting the content-type header, and ReceiveJson deserializes the response. 它的PostJsonAsync方法负责序列化内容和设置content-type标头,而ReceiveJson反序列化响应。 If the accept header is required you'll need to set that yourself, but Flurl provides a pretty clean way to do that too: 如果需要accept标头,则需要自己设置,但Flurl也提供了一种非常干净的方法:

using Flurl.Http;

var result = await "http://example.com/"
    .WithHeader("Accept", "application/json")
    .PostJsonAsync(new { ... })
    .ReceiveJson<TResult>();

Flurl uses HttpClient and Json.NET under the hood, and it's a PCL so it'll work on a variety of platforms. Flurl在后台使用HttpClient和Json.NET,它是PCL,因此可以在各种平台上工作。

PM> Install-Package Flurl.Http

#6楼

try to use TryAddWithoutValidation 尝试使用TryAddWithoutValidation

  var client = new HttpClient();
  client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当你在发送HTTP请求设置`Content-Type`头部,有时候可能会遇到错误,这通常是因为以下几个原因: 1. **拼写或格式错误**:检查`Content-Type`字段是否正确拼写,例如应该是`"application/json"`而不是`"application/json;"`。确保没有额外的空格或分号。 2. **无效的内容类型**:确保你正在使用的MIME类型对应于你的数据格式。比如,如果你传递的是JSON数据,应设置`Content-Type: application/json`,而非文本或其他非预期类型。 3. **跨域问题**:如果在浏览器环境中,可能存在同源策略限制。除非服务器允许,否则你无法直接向其他域名发送带有特定`Content-Type`的请求。 4. **HttpClient配置**:如果你使用的是`HttpClient`,可能需要显式配置它的`DefaultRequestHeaders.ContentType`属性。确保你是在适当的时间点设置,并且是在构建请求前进行。 5. **请求方法不匹配**:如果是POST、PUT等需要携带内容类型的请求,确保方法与内容类型相匹配。GET请求通常不需要指定`Content-Type`,因为它默认为`text/plain`. 一个正确的例子: ```csharp using HttpClientHandler = System.Net.Http.HttpClientHandler; // 如果你使用的是.Net Framework,请替换为HttpClientHandler using HttpResponseMessage = System.Net.Http.HttpResponseMessage; // 同上 HttpClient client = new HttpClient(new HttpClientHandler()); client.DefaultRequestHeaders.ContentType = MediaTypeHeaderValue.Parse("application/json"); // 这里设置Content-Type string jsonPayload = "{\"key\":\"value\"}"; var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await client.PostAsync("https://api.example.com/endpoint", content); // ... } catch (HttpRequestException e) { Console.WriteLine($"Request failed with status code: {e.Response?.StatusCode}"); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值