在Android中使用Google Translate API [英] Usage of Google Translate API in Android

查看:516
本文介绍了在Android中使用Google Translate API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在互联网上搜索谷歌翻译API的使用情况,但是我找不到下降教程或解释。所以,这就是我所做的:


在我的Google API控制台中,我使用



在Android Studio中,我使用OkHttp库构建并发送我的请求使用以下代码:

  OkHttpClient client = new OkHttpClient(); 
String apiKey =我的API密钥;
String apiLangSource =en;
String apiLangTarget =de;
String apiWord =Hello;
String googleApiUrl =https://www.googleapis.com/language/translate/v2?key=+ apiKey +& source =+ apiLangSource +& target =+ apiLangTarget +& amp ; q =+ apiWord;
Request request = new Request.Builder()。url(googleApiUrl).build();

Log.d(标签,API STRING+ googleApiUrl);

呼叫电话= client.newCall(request);

call.enqueue(new Callback(){
@Override
public void onFailure(Request request,IOException e){
Log.d(TAG,HTTP CALL FAIL);
}

@Override
public void onResponse(响应响应)抛出IOException {
Log.d(TAG,response.body())。 string());

}
});

它运行良好,但我得到的回应是:

  {
error:{
errors:[
{
domain:usageLimits,
reason:ipRefererBlocked,
message:您的API密钥上配置了per-IP或per-Referer限制,请求与这些限制不符。请使用Google Developers Console更新您的API密钥配置,如果来自这个IP或referer的请求应该被允许。,
extendedHelp:https://console.developers.google.com
}
] ,
code:403,
message:您的API密钥上配置了per-IP或per-Referer限制,请求不符合这些限制,请使用Google Developers如果允许来自此IP或引用者的请求,控制台可更新您的API密钥配置。




问题是什么这里?我的API设置正确吗?我是否正确拨打了电话(我看过一些图书馆,但带着导游)?这是使用这个库的合理方式吗?这是什么意思?

 您的API密钥上配置了每IP或每个Referer限制,并且请求不符合这些限制。如果允许来自此IP或引荐者的请求,请使用Google Developers Console更新您的API密钥配置。 

我认为有一些免费的演示调用,这不是问题。解决方案

解决方案问题是在为Android应用程序设置API密钥限制时,您指定了软件包名称和SHA-1证书指纹。因此,您的API密钥只会接受您的应用程序发出的包名和指定的SHA-1证书指纹的请求。

所以,google如何知道请求是从您的Android应用程序发送的?您必须在每个请求的头部添加应用程序的包名称和SHA-1,并使用以下键:

键:X-Android-Package ,value:您的应用程序包名称



键:X-Android-Cert,值:您的apk的SHA-1证书

首先,获取您的应用SHA签名(您需要番石榴图书馆):

  / * * 
*获取SHA1签名,十六进制编码用于包含Google Cloud Platform API请求
*
* @param packageName标识要提取签名的APK。
* @返回一个小写,十六进制编码的
* /
public static String getSignature(@NonNull PackageManager pm,@NonNull String packageName){
try {
PackageInfo packageInfo = pm.getPackageInfo(packageName,PackageManager.GET_SIGNATURES);
if(packageInfo == null
|| packageInfo.signatures == null
|| packageInfo.signatures.length == 0
|| packageInfo.signatures [0] == null){
return null;
}
返回signatureDigest(packageInfo.signatures [0]);
} catch(PackageManager.NameNotFoundException e){
return null;



private static String signatureDigest(Signature sig){
byte [] signature = sig.toByteArray();
尝试{
MessageDigest md = MessageDigest.getInstance(SHA1);
byte [] digest = md.digest(signature);
返回BaseEncoding.base16()。lowerCase()。encode(digest);
} catch(NoSuchAlgorithmException e){
return null;


$ / code>

然后,添加软件包名称和SHA证书签名以请求header:

  java.net.URL url = new URL(REQUEST_URL); 
HttpURLConnection连接=(HttpURLConnection)url.openConnection();
尝试{
connection.setDoInput(true);
connection.setDoOutput(true);

connection.setRequestProperty(Content-Type,application / json; charset = UTF-8);
connection.setRequestProperty(Accept,application / json);

//将软件包名称添加到请求头文件
String packageName = mActivity.getPackageName();
connection.setRequestProperty(X-Android-Package,packageName);
//添加SHA证书来请求头文件
String sig = getSignature(mActivity.getPackageManager(),packageName);
connection.setRequestProperty(X-Android-Cert,sig);
connection.setRequestMethod(POST);

//将您的请求添加到此处
// ....................
} catch(Exception e ){
e.printStackTrace();
} finally {
connection.disconnect();
}

希望得到这个帮助! :)

I have been searching everywhere on the Internet for Google Translate API usage but I wasn't able find descent tutorial or explanation. So, here is what I have done:

In my Google API Console I have generated a key under Public API access with my SHA1 Fingerprint using this answer. Here is how my API console looks like:

In Android studio I build and send my request using OkHttp library with this code:

OkHttpClient client = new OkHttpClient();
    String apiKey = "My API key";
    String apiLangSource = "en";
    String apiLangTarget = "de";
    String apiWord = "Hello";
    String googleApiUrl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&source=" + apiLangSource + "&target=" + apiLangTarget + "&q=" + apiWord;
    Request request = new Request.Builder().url(googleApiUrl).build();

    Log.d(TAG, "API STRING" + googleApiUrl);

    Call call = client.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            Log.d(TAG , "HTTP CALL FAIL");
        }

        @Override
        public void onResponse(Response response) throws IOException {
            Log.d(TAG , response.body().string());

        }
    });

It runs fine but on response I get:

{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "ipRefererBlocked",
"message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.",
"extendedHelp": "https://console.developers.google.com"
}
],
"code": 403,
"message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."
}
}


What is the problem here? Is my API set up correctly? Am I making the call correctly (I've seen some libraries but with guide)? Is this reasonable way of using this library? What exacty does this mean?

"There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."

I think there are some demo calls available for free and this isn't the problem here.

解决方案

Problem is when setting up your API key restriction for android app, you specified the package name and SHA-1 certificate fingerprint. Therefore your API key will only accept request from your app with package name and SHA-1 certificate fingerprint specified.

So how google know that request's sent FROM YOUR ANDROID APP? You MUST add your app's package name and SHA-1 in the header of each request with following keys:

Key: "X-Android-Package", value: your app package name

Key: "X-Android-Cert", value: SHA-1 certificate of your apk

FIRST, get your app SHA signature (you will need Guava library):

/**
 * Gets the SHA1 signature, hex encoded for inclusion with Google Cloud Platform API requests
 *
 * @param packageName Identifies the APK whose signature should be extracted.
 * @return a lowercase, hex-encoded
 */
public static String getSignature(@NonNull PackageManager pm, @NonNull String packageName) {
    try {
        PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
        if (packageInfo == null
                || packageInfo.signatures == null
                || packageInfo.signatures.length == 0
                || packageInfo.signatures[0] == null) {
            return null;
        }
        return signatureDigest(packageInfo.signatures[0]);
    } catch (PackageManager.NameNotFoundException e) {
        return null;
    }
}

private static String signatureDigest(Signature sig) {
    byte[] signature = sig.toByteArray();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        byte[] digest = md.digest(signature);
        return BaseEncoding.base16().lowerCase().encode(digest);
    } catch (NoSuchAlgorithmException e) {
        return null;
    }
}

Then, add package name and SHA certificate signature to request header:

java.net.URL url = new URL(REQUEST_URL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
    connection.setDoInput(true);
    connection.setDoOutput(true);

    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    connection.setRequestProperty("Accept", "application/json");

    // add package name to request header
    String packageName = mActivity.getPackageName();
    connection.setRequestProperty("X-Android-Package", packageName);
    // add SHA certificate to request header
    String sig = getSignature(mActivity.getPackageManager(), packageName);
    connection.setRequestProperty("X-Android-Cert", sig);
    connection.setRequestMethod("POST");

    // ADD YOUR REQUEST BODY HERE
    // ....................
} catch (Exception e) {
    e.printStackTrace();
} finally {
    connection.disconnect();
}

Hope this help! :)

这篇关于在Android中使用Google Translate API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆