0

I have to send an request with an image to Microsoft Azure Custom Vision with the header "Prediciton-Key" -> myKey and the body should be an image (binary data).

First of all i tryed with postman and it works fine, but when i put it on Unity ,i get an error :401 Unauthorized.

Does anyone know why? (i put the api key as string)

    WWWForm form = new WWWForm();
    form.headers.Add("Prediction-Key", "xxxxxxxxxxxxxxxxxxxxxxxx");
    form.AddBinaryData("fileUpload", texture.EncodeToPNG());

   UnityWebRequest req = UnityWebRequest.Post(link,form);

    yield return req.SendWebRequest();
  • `Prediciton-Key` That is a different spelling to your code. – mjwills Jan 09 '19 at 12:38
  • Use a sniffer and compare postman results with your results. There is probably a difference in the header in the request. Solution is to make you headers look like the postman headers. – jdweng Jan 09 '19 at 12:45
  • In the instructions is highlighted "Prediction-Key" It's a little weird because if i use WWW instead of UnityWebRequest all is good. – Vlad Constantinescu Jan 09 '19 at 13:00

1 Answers1

0

In the docu they actually didn't show any example for using the Prediction-Key but I guess it works similar to the examples with Training-Key e.g.:

curl -X POST "https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Training/projects/{projectId}/tags?name=cat" -H "Training-Key: $TRAININGKEY" --data-ascii ""

The header after -H is a header added to the http-request itself not as a header field within the form.

I'm pretty sure you have to use a base64 encoded string similar to when adding authorization headers (Source)

string Base64String(string key)
{
    return System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(key));
}

and than use it req.SetRequestHeader in order to authorize the http-request itself not as header in the form:

WWWForm form = new WWWForm();
form.AddBinaryData("fileUpload", texture.EncodeToPNG());

UnityWebRequest req = UnityWebRequest.Post(link,form);
req.SetRequestHeader("Prediction-Key", Base64String("xxxxxxxxxxxxxxxxxxxxxxxx");

yield return req.SendWebRequest();
derHugo
  • 83,094
  • 9
  • 75
  • 115