Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

c# - 如何设置HttpClient请求的Content-Type标头?(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标头?)

  ask by mynameiscoffey translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...