I'm trying to set the Content-Type
header of an HttpClient
object as required by an API I am calling.
I tried setting the Content-Type
like below:
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:
Misused header name. Make sure request headers are used with
HttpRequestMessage
, response headers withHttpResponseMessage
, and content headers withHttpContent
objects.
How can I set the Content-Type
header in a HttpClient
request?
In versions pre 4.3 of HttpClient, we can set any custom header on a request with a simple setHeader call on the request: HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(SAMPLE_URL); request. setHeader(HttpHeaders. CONTENT_TYPE, "application/json"); client.
The Content-Type representation header is used to indicate the original media type of the resource (prior to any content encoding applied for sending). In responses, a Content-Type header provides the client with the actual content type of the returned content.
Nope, Content-Type is not a required field. It's not mandatory per the HTTP 1.1 specification. Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body.
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); });
For those who didn't see Johns comment to carlos solution ...
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With