Microsoft Cognitive Services - Authentication Issues, Unable to get Access Token

771 views Asked by At

I am trying to call ms cognitive service from android. However, the api to get access token is not working.. below is the android code

HttpPost httpPost = new HttpPost("https://api.cognitive.microsoft.com/sts/v1.0/issueToken");


List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("Ocp-Apim-Subscription-Key", "my subscription key"));

try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {

}

try {
    HttpResponse response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

In logcat, i get the error:

java.net.UnknownHostException: Unable to resolve host "api.cognitive.microsoft.com": No address associated with hostname

Is there any change to api url "https://api.cognitive.microsoft.com/sts/v1.0/issueToken"?

Also, when i type this URL "https://api.cognitive.microsoft.com/sts/v1.0/issueToken" in browser, I get the message

{ "statusCode": 404, "message": "Resource not found" }

Please help.

1

There are 1 answers

2
Peter Pan On BEST ANSWER

As I known, there is not any change to api url https://api.cognitive.microsoft.com/sts/v1.0/issueToken, as the same as the content described in the link.

I tried to call the api via the tool Postmanenter image description here and successfully got the token, as below.

You couldn't get the result as your hope via type url in browser, because the api call is a POST request, not a GET request via nagetive a url in browser.

Per your code, seems that the issue was caused by missing the required content length Content-Length: 0.

As reference, here is my sample code which works.

URL url = new URL("https://api.cognitive.microsoft.com/sts/v1.0/issueToken");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Ocp-Apim-Subscription-Key", "XXXXXXXX");
conn.setRequestMethod("POST"); 
conn.setDoOutput(true); // Must set do output true
conn.setFixedLengthStreamingMode(0); // Set Content-Length 0
conn.connect();
int code = conn.getResponseCode();
String msg = conn.getResponseMessage();
System.out.println(code+"\t"+msg);
IOUtils.copy(conn.getInputStream(), System.out);

The response as below for the above code.

200 OK
eyXXXXXXXXXXXXXXXXXXXXXXXXXX