8

Hi I'm trying to trigger a POST call to the following API. and here's code

var client = new HttpClient();

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);

var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString["returnFaceId"] = "true";
queryString["returnFaceLandmarks"] = "false";
queryString["returnFaceAttributes"] = "age,gender";

var filebytes = File.ReadAllBytes(@"C:\Users\user1\Desktop\IMG.jpg");

var uri = "https://southeastasia.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;

HttpResponseMessage response;


using (var content = new ByteArrayContent(filebytes))
{
    response = client.PostAsync(uri, content).Result;
    var result = response.Content.ReadAsStringAsync().Result;
}

I get the following error in result:

{"error":{"code":"BadArgument","message":"JSON parsing error."}}

This code works fine if I use application/json, and pass a http link.

Henrik Wilshusen
  • 289
  • 1
  • 11
Null Reference
  • 11,260
  • 40
  • 107
  • 184

2 Answers2

9

As the example code given by Microsoft, can you try to set ContentType like the sample :

using (var content = new ByteArrayContent(byteData))
{
     content.Headers.ContentType = new MediaTypeHeaderValue("< your content type, i.e. application/json >");
     response = await client.PostAsync(uri, content);
}
Antoine V
  • 6,998
  • 2
  • 11
  • 34
  • 2
    For whom be using this with Azure Computer Vision API (OCR / Read), and posting a binary data (image), the line should be `content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");` – Vitox Dec 16 '20 at 07:42
3

Try to set request content type as "application/octet-stream".

Rui Fernandes
  • 270
  • 1
  • 11
  • isn't it set this way client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));? – Null Reference Aug 14 '18 at 09:42
  • 1
    _"Accept: is what the browser is able to digest, for example, all the languages someone can understand."_ _"Content-Type: is what format the actual data is in, for example what language someone is speaking. Since computers can't (well, now they can) recognize other types like people can say "oh, he's German!" or "she's speaking Chinese!""_ from [here](https://webmasters.stackexchange.com/questions/31212/difference-between-the-accept-and-content-type-http-headers#31231) – Rui Fernandes Aug 14 '18 at 09:46