0

When testing the call through Postman and a C# WebRequest it works, but I am unable to do the same using an HttpClient with a PostAsync or PostJsonAsync call.

Error: Unsupported Media Type, although application/json is required and applied.

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders
                    .Accept
                    .Add(new MediaTypeWithQualityHeaderValue("application/json"));

var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://pos.api.here.com/positioning/v1/locate?app_id={id}&app_code={code}", content);
return response;

StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:{ Date: Fri, 08 Nov 2019 13:38:37 GMT Server: nginx-clojure Content-Type: application/json Content-Length: 114}

WebRequest

HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
if (!string.IsNullOrEmpty(data))
{
    request.ContentType =  "application/json";
    request.Method =  "POST";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(data);
        streamWriter.Flush();
        streamWriter.Close();
    }
}

using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
{
    using (StreamReader reader = new StreamReader(webresponse.GetResponseStream()))
    {
        string response = reader.ReadToEnd();
        return response;
    }
}
Anton Swanevelder
  • 1,025
  • 1
  • 14
  • 31

1 Answers1

1

There are two differences I see:

  1. You are setting the Accept header in your HttpClient code, where you were not in your WebRequest code. This defines the type of data that you accept. If this API call does not return JSON, then it could be just saying "I have nothing to say to you then". You can try just deleting that whole line.
  2. The Content-Type in your HttpClient code will be application/json; charset=utf-8, whereas you set it to just application/json in your WebRequest code. I don't see why the charset would make it choke, but if changing #1 doesn't work, you can try setting the Content-Type directly and see if it makes any difference:
var content = new StringContent("");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84