Reputation: 9912
When using HttpClient
, I have read examples (such as this example) that uses DefaultRequestHeaders
to set the content type (such as "application/json") of a Post request.
I tried to do something like this, but it failed. The API
I am sending requests complained that it was sent an "unsupported type" (which it says when the content type is not set to json
).
After that I added one line and I solved the issue (you can see the line in the code below commented).
My question is why is this line necessary? And if I include this line (that is setting the content type of the content) doesn't that make the "default request header" setting unnecessary. What is this "default request header" doing if anything?
(I actually tried and commented the lines related to DefaultRequestHeaders
and it worked without problem. So what is DefaultRequestHeaders
good for?)
My code is :
// Get the bytes for the request, should be pre-escaped
byte[] bytes = Encoding.UTF8.GetBytes(jsonEmployeeData);
client.BaseAddress = new Uri("the address here");
// client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("customHeader", "blahblahblah");
ByteArrayContent byteContent = new ByteArrayContent(bytes); //Make a new instance of HttpContent (an abstract class that can't be instantiated)
//THIS is the solution
//byteContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json"); //If I UNCOMMENT THIS, IT WORKS!!
try
{
HttpResponseMessage response = await client.PostAsync("staff", byteContent);
Console.WriteLine(response.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Something happened, oopps!" + ex.Message);
}
Console.WriteLine("Press any key");
Console.ReadLine();
client
is a HttpClient
by the way.
Upvotes: -1
Views: 2976
Reputation: 1528
The API you called needs the request content is application/json format, so you have to specify this format in your content. That's why that line of code is the one you need:
byteContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
About the line:
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"))
This is request Accept header, it means the content type of response which you expect the server return to you. (You can expect server returns another content type like text/plain,...). Hope this helps!
Upvotes: 2