如何在Android应用程序中使用Google公共API访问密钥? [英] How to use Google public API access key in android application?

查看:77
本文介绍了如何在Android应用程序中使用Google公共API访问密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use Google Translate API (v2) in my android application.

我做了什么:

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

  1. created project in Google Developers Console
  2. set up billing for this project
  3. generated 2 public api access keys for android applications:

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

a. First one that accepts request from any application

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

b. Second one that accepts requests from my application only

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

I tried to translate text from the application via https://www.googleapis.com/language/translate/v2?key=MY-KEY&target=de&q=Hello%20world

它与3a)中的键一起工作正常,但不适用于3b)中的键.对于3b)服务器发送

It works fine with the key from 3a) but does not work with the key from 3b). For 3b) server sends

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

我想这是因为Google服务器在此请求下未收到有关我的应用程序的任何信息,因此无法获取密钥3b).如果是这样,如何正确发送此请求?或者,或者,我在其他地方做错了什么?

I guess this is because google server does not receive any info about my application with this request, so it cannot acquire key 3b). If so, how to send this request correctly? Or, alternatively, what I did wrong somewhere else?

推荐答案

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

If so, how to send this request correctly?

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

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.

如何?

在此处回答,您需要从代码中获取软件包名称和SHA证书,然后添加到请求标头中.

As answered here, you need to get your package name and SHA certificate from your code, and then adding to request header.

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

您可以看到完整的答案这里.

You can see full answer here.

享受编码:)

这篇关于如何在Android应用程序中使用Google公共API访问密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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