在Android

时间:2015-07-23 11:42:35

标签: android google-api google-translate

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

在我的Google API控制台中,我使用this答案使用SHA1指纹在Public API访问下生成了一个键。以下是我的API控制台的外观: Google console

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

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

1 个答案:

答案 0 :(得分:1)

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

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

键:"X-Android-Package",值:您的应用包名称

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

希望这有帮助! :)