Issue getting the azure translator to work with Android

182 views Asked by At

My android app used the old microsoft Translator very well but I am having problems getting the app to work with the new Cognitive Services.

First I got a new azure translation account that has the following values (these are not the real values)

Name: MYTranslateAcct

Resource group: translate

subscription ID: 981h5ce7-7ac7-4f6f-b4a5-ff04dc9e4266

key1 d122230418a8479ab5c06f2f1fca664c

key2 39c1f187o9814f4e983jba9eedd2e2c7

My first step is to try to get a token. Microsoft has docs on doing this in JAVA but not in an Android environment. I dug around and have put together some code but it is not working. One problem is that the docs use terms that I don't have in my account such as "app-id" and "key". I don't have those things - I just have the list of values above.

Here is my code . . .

class translateMessage extends AsyncTask<Void, Void, String>
{
    String retString;
    String inString = null;

    translateMessage(String inString) { this.inString = inString; }
    @Override
    protected String doInBackground(Void... arg0)
    {
        try
        {


            String key = "881b5ce7-9ac7-4f6f-b4a5-ff04dc9e3199";
            String authenticationUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
            HttpsURLConnection authConn = (HttpsURLConnection) new URL(authenticationUrl).openConnection();
            authConn.setRequestMethod("POST");
            authConn.setDoOutput(true);
            authConn.setRequestProperty("Ocp-Apim-Subscription-Key", key);
            IOUtils.write("", authConn.getOutputStream(), "UTF-8");       //following line of code gets the exception . . .
            String token = IOUtils.toString(authConn.getInputStream(), "UTF-8");  //this blows
       }
        catch (Exception e)
        {
            String myString = e.getMessage();
            String aString = "look at e";

        }
        return retString;
    }

    @Override
    protected void onPostExecute(String result)
    {
        String debugStr = result;
        translation.setText(result);
    }
}

Following is the exception . . .

java.io.FileNotFoundException:https://api.cognitive.microsoft.com/sts/v1.0/issueToken

What am I doing wrong? Is anyone aware of any working Android java code using the new services?

1

There are 1 answers

0
Dean Blakely On

I posted this on Azure support and someone called me within an hour. I was passing the wrong key. When you get a translate cognitive account you get Key1 and Key2. Either of them will work. So the code is a useful example of working code that will get a token.