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

强颜欢笑 提交于 2020-08-14 16:26:46

问题:

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标头?


解决方案:

参考一: https://stackoom.com/question/io9O/如何设置HttpClient请求的Content-Type标头
参考二: https://oldbug.net/q/io9O/How-do-you-set-the-Content-Type-header-for-an-HttpClient-request
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!