I am working with a RESTful API that supports POST requests in JSON format. The API's own Swagger documentation shows that this is a valid call to one of its endpoints:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '<JSON>' '<URL>'
Where <JSON>
and <URL>
are the valid JSON message and the endpoint's URL. From this Swagger documentation I gather that any posts to this endpoint must include both a Content-Type
and Accept
headers set to application/json
.
I am writing a C# method that will use .NET Core's HttpClient
class to post to this endpoint. However, upon posting my message I receive an HTTP 415 error code back, for Unsupported Media Type. From what I've learned so far, the Content-Type
header must be set in your content (I am using the StringContent
class) and the Accept
header can only be set in the HttpClient
headers. Here is my particular example:
var httpContent = new StringContent("<JSON>", Encoding.UTF32, "application/json");
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseMessage = httpClient.PostAsync("<URL>", httpContent);
var result = responseMessage.Result;
Once again, where <JSON>
and <URL>
are the valid JSON message and the endpoints's URL. It would seem to me that the third line, on which I reference httpCllient.DefaultRequestHeaders
, is not adding the Accept: application/json
header to my request. If I manually add the header to the httpContent.Headers
collection, I get a run-time error that tells me that Accept
is not a header I can add to the httpContent
. That's why I am hoping to add it to the httpClient
instead.
I have validated the URL and my JSON with Swagger, so I know those are correct. Also, the request is done over HTTPS, so I can't use Fiddler to validate that the Accept
header is being included. And while I could enable decryption in Fiddler, that's a whole other ball of wax. I don't want to add their root certificate to my system, especially if I'm missing something fairly simple, which this seems to be.
Any pointers will be appreciated. Thanks.
what about if you try:
var httpContent = new StringContent(jsonData, Encoding.UTF8, "application/json");
You shouldn't need to add an Accept header.