我正在尝试根据我正在调用的 API 的要求设置对象的Content-Type标头。HttpClient
Content-Type
HttpClient
我尝试设置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它时会引发以下异常:
Accept
误用的标头名称。确保请求标头与 一起使用 HttpRequestMessage,响应标头与 一起使用HttpResponseMessage,内容标头与HttpContent对象一起使用。
HttpRequestMessage
HttpResponseMessage
HttpContent
如何Content-Type在HttpClient请求中设置标头?
内容类型是内容的标头,而不是请求的标头,这就是失败的原因。AddWithoutValidation正如 Robert Levy 所建议的那样可能有效,但您也可以在创建请求内容本身时设置内容类型(请注意,代码片段application/json在两个地方添加了 Accept 和 Content-Type 标头):
AddWithoutValidation
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); });