I've been trying to get the Google Translate API working. I have read and re-read a number of posts, as well as the Google Cloud authentication guide (http://cloud.google.com/docs/authentication/getting-started#auth-cloud-implicit-java) but still must be missing something. As per the guide and following http://stackoverflow.com/questions/49379897/missing-a-valid-api-key-about-google-translation-api-client-issue , I created a Service Account called ABCD and made myself project owner in the GCP Console. I downloaded the JSON file and placed it in a folder called JSON. I then created a system environment variable manually-GOOGLE_APPLICATION_CREDENTIALS with a value of C:\Users\aaa\AndroidStudioProjects\JSON.
When I look at the IAM & admin page in the GCP console, it shows my service account, with an id of ABCD@helpful-monitorxxxxxxxxx.com as well as the Key Id.
Here is my MainActivity class as well as an Aync task class to do the translation.
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context context = getApplicationContext();
Trans translate = new Trans();
String text = ("Hello world");
String res = translate.execute(text).toString();
}
}
import android.os.AsyncTask;
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;
public class Transl extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
String text = "Hello friend"; //text to translate
Translate translate = TranslateOptions.getDefaultInstance().getService();
Translation translation =
translate.translate(
text,
Translate.TranslateOption.sourceLanguage("en"),
Translate.TranslateOption.targetLanguage("fr"));
return translation.getTranslatedText();Fatal Exception
}
protected void onPostExecute(String result) {
System.out.printf("Translation: %s%n", result);
}
}
When I run it, I get a Fatal RunTime exception-
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "The request is missing a valid API key.",
"reason" : "forbidden"
} ],
"message" : "The request is missing a valid API key.",
"status" : "PERMISSION_DENIED"
}
I can't really find any way to debug it. Do I need to do something further to enable the account/API key? Is there code missing?
Thanks for your support.