问题
I've been getting error 403 - Requests from this Android client application are blocked using paid Google Cloud Platform Translation API. Works great when restrictions are set to none. There are a few threads around reporting similar issue, but none answered.
I've seen in some examples, there's a version which had .setApplicationName(), I think that might help, but I can't find which version would that be.
Code used is:`
private void translate(String textToTranslate, String targetLanguage, TranslateCallback callback) {
try {
TranslateOptions options = TranslateOptions.newBuilder()
.setApiKey( < api_key >)
.build();
Translate trService = options.getService();
Translation translation = trService.translate(textToTranslate,TranslateOption.targetLanguage(targetLanguage));
callback.onSuccess(translation.getTranslatedText());
}
catch(Exception e) {
callback.onFailure();
}
}`
from: https://medium.com/@amsanjeev/adding-translate-api-to-android-apps-788c5bca5521
回答1:
Finally I found a way.
When setting up your API key restriction for android app, you specified the package name and SHA-1 certificate fingerprint. So when you send an request to Google, you must add these information in the header of each request.
connection.setRequestProperty("X-Android-Package", "com.example.awesomeapp");
String sign = "5D:5A:12:D3:......".toLowerCase(); //Your SHA1 key in lower cased.
connection.setRequestProperty("X-Android-Cert", sig);
A detailed answer can be found here.
来源:https://stackoverflow.com/questions/49958986/google-translate-api-requests-from-this-client-application-empty-are-blocked