【问题标题】:How to use Google public API access key in android application?如何在 Android 应用程序中使用 Google 公共 API 访问密钥?
【发布时间】:2015-08-19 18:44:35
【问题描述】:

我想在我的 Android 应用程序中使用 Google Translate API (v2)。

我做了什么:

  1. 在 Google Developers Console 中创建项目
  2. 为此项目设置帐单
  3. 为 android 应用程序生成 2 个公共 api 访问密钥:

    一个。第一个接受来自任何应用程序的请求

    b.第二个只接受来自我的应用程序的请求

我尝试通过以下方式翻译应用程序中的文本 https://www.googleapis.com/language/translate/v2?key=MY-KEY&target=de&q=Hello%20world

它适用于 3a) 中的密钥,但不适用于 3b) 中的密钥。对于 3b) 服务器发送

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

我猜这是因为谷歌服务器没有收到关于我的应用程序的任何信息,所以它无法获取密钥 3b)。如果是这样,如何正确发送此请求?或者,或者,我在其他地方做错了什么?

【问题讨论】:

    标签: android google-translate


    【解决方案1】:

    如果是,如何正确发送这个请求?

    在为 Android 应用设置 API 密钥限制时,您指定了包名称和 SHA-1 证书指纹。因此,当您向 Google 发送请求时,您必须在每个请求的标头中添加这些信息。

    怎么做?

    As answered here,你需要从你的代码中获取你的包名和SHA证书,然后添加到请求头中。

    获取 SHA 证书:

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

    添加到请求头:

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

    你可以看到完整的答案here

    享受编码:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 2014-08-09
      • 1970-01-01
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多