【问题标题】:Usage of Google Translate API in AndroidAndroid 中谷歌翻译 API 的使用
【发布时间】:2015-10-13 16:46:07
【问题描述】:

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

在我的 Google API 控制台中,我使用this 答案在我的 SHA1 指纹的公共 API 访问下生成了一个密钥。这是我的 API 控制台的样子:

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

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());

        }
    });

它运行良好,但响应我得到:

{
"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."
}
}


这里有什么问题?我的 API 设置是否正确?我是否正确拨打电话(我看过一些图书馆但有指南)?这是使用这个库的合理方式吗?这究竟是什么意思?

"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."

我认为有一些免费的演示电话可用,这不是问题所在。

【问题讨论】:

  • 我猜你的 API 配置没有做好。你可以看到回复restriction configured on your API key and the request does not match
  • 当我移除指纹并打包时,它可以工作。所以这确实是身份验证错误。谷歌如何验证我的指纹和包裹?
  • 我遇到了同样的问题。 @DannyBabbev,你找到解决方案了吗?
  • 我还没有找到解决办法。

标签: android google-api google-translate


【解决方案1】:

问题是在为 Android 应用设置 API 密钥限制时,您指定了包名称和 SHA-1 证书指纹。因此,您的 API 密钥将仅接受来自您的应用的请求,并指定了包名称和 SHA-1 证书指纹。

那么 google 是如何知道该请求是从您的 ANDROID 应用程序发送的?您必须使用以下键在每个请求的标头中添加应用的包名称和 SHA-1:

Key:"X-Android-Package",value:你的应用包名

密钥:"X-Android-Cert",值:您的 apk 的 SHA-1 证书

首先,获取您的应用 SHA 签名(您将需要 Guava 库):

/**
 * 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;
    }
}

然后,将包名和SHA证书签名添加到请求头中:

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();
}

希望对您有所帮助! :)

【讨论】:

    猜你喜欢
    • 2013-02-15
    • 1970-01-01
    • 2011-06-06
    • 2011-12-26
    • 2010-10-10
    • 1970-01-01
    • 2019-02-10
    相关资源
    最近更新 更多