I'm developing a Windows 8.1 Store apps with C# and .NET Framework 4.5.1.
I'm trying to do a POST to a REST API but I get an Unsupported Media Type with this code:
public async Task<HttpResponseMessage> POST(string url, string jsonContent)
{
Uri resourceUri;
resourceUri = ValidateUri(url);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
HttpRequestHeaderCollection headers = httpClient.DefaultRequestHeaders;
// Try to add user agent to headers.
if (headers.UserAgent.TryParseAdd(_userAgent))
headers.UserAgent.ParseAdd(_userAgent);
// Add Content-Type and Content-Length headers
headers.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));
return response;
}
If I change this line:
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));
With this one:
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(string.Empty));
It works. I don't get 415 status code.
jsonContent
value is:
{"UserName":"My Name","Provider":"Facebook","ExternalAccessToken":"Access token omitted"}
Because I haven't found any similar code on Internet, and I only have 4 views on this question; I will share the answer.
I have fixed this problem changing the post with this code:
response = await httpClient.PostAsync(resourceUri,
new HttpStringContent(jsonContent, UnicodeEncoding.Utf8, "application/json"));
You can pass "Content-Type" on HttpStringContent
constructor. More info here.