[Java] - Google API調用


由於Google已經完成被牆,要上Google必需使用代理或VPN。

這里使用的是Google的GoAgent代理做開發。(如何使用GoAgent,這里不寫了,忽略500字。。。。。)

本地測試的GoAgent地址為:127.0.0.1:8087


 

 

一、Google的API設置

1、首先需要在Google的控制台中設置新增好Project,設置地址:

https://console.developers.google.com

 

2、在Permissions中設置好Service Account:

 

3、在APIs & Auth -> APIs中,加入所需要開放的API,如本例中使用的是ShoppingContent:

 

4、在APIs & Auth -> credential中生成或新增對應的鍵值或證書:

我這里使用的是證書形式的調用,證書的生成在Public API access當中。點生成證書key后,會導出一個p12證書。保存好這個證書到項目當中。


 

 

二、獲取Google HTTPS證書,並導入到Java JRE里頭信認此證書

因為使用java訪問google API是以https形式訪問的,默認情況下,google的證書是不被信認的。所以需要先把google https的證書添加到java信認證書當中。

1、首先使用chrome打開這個地址:https://accounts.google.com

 

2、點擊地址欄上的綠色鎖:

 

3、導出https證書保存成文件:

比如說我這里保存的文件是:google.cer

 

4、eclipse安裝插件:net.sourceforge.keytool.plugin_1.4.2.jar

插件哪里下載,自行搜索。在http://sourceforge.net/中可以下到。

如何安裝eclipse插件這里忽略。

安裝完后,可以在eclipse中看到:

工具欄:

下面窗口:

 

5、打開java的jdk證書文件,在eclipse中:

彈出窗口:

例如我本機的FileName中的位置是:C:\Program Files\Java\jdk1.7.0_51\jre\lib\security\cacerts

這里不要選錯了,是JDK下的JRE下的lib,不要直接選到JRE下的lib。

默認密碼為:changeit

打開后,將看到如下內容:

 

6、導入證書。右鍵->Import certificate

成功導入后將看到:


 

 

三、編碼

1、eclipse新建一個maven項目。(如何在eclipse新建maven項目這里忽略,使用maven是方便下載jar包,也可以自行上網搜索下載比較煩鎖)

這里使用的是Google API的ShoppingContent做例子,所以下的Jar包為ShoppingContent,使用別的API,需要自行修改

pom.xml內容為:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.my.maven.googleapi</groupId>
  <artifactId>testapi</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>testapi</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>1.19.0</version>
    </dependency>
    <dependency>
        <groupId>com.google.http-client</groupId>
        <artifactId>google-http-client-jackson2</artifactId>
        <version>1.19.0</version>
    </dependency>
    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-content</artifactId>
      <version>v2-rev33-1.19.1</version>
    </dependency>
  </dependencies>
</project>

下載完后的jar包大致會有這些:

 

2、把p12證書文件也放到項目當中:

 

3、Java測試類:

package com.my.maven.googleapi.testapi;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Properties;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.content.ShoppingContent;
import com.google.api.services.content.ShoppingContentScopes;
import com.google.api.services.content.model.Product;

/**
 * Hello world!
 * 
 */
public class App {

    public static void main(String[] args) throws Exception {

        String strJavaHome = System.getProperty("java.home");

        Properties systemProperties = System.getProperties();
        systemProperties.setProperty("http.proxyHost", "127.0.0.1");
        systemProperties.setProperty("http.proxyPort", "8087");
        systemProperties.setProperty("https.proxyHost", "127.0.0.1");
        systemProperties.setProperty("https.proxyPort", "8087");
        systemProperties.setProperty("socksProxyHost", "127.0.0.1");
        systemProperties.setProperty("socksProxyPort", "8087");
        System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(900000));// (單位:毫秒)

        final Credential credential = authorize();
        ShoppingContent service = new ShoppingContent.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
//                .setHttpRequestInitializer(new HttpRequestInitializer() {
//                    public void initialize(HttpRequest httpRequest) throws IOException {
//                        httpRequest.setReadTimeout(90000000);
//                        credential.initialize(httpRequest);
//                    }
//                })
                .build();
        Product product = service.products()
                .get(merchantId, "online:en:JP:123456789").execute();
        System.out.printf("%s %s\n", product.getId(), product.getTitle());
    }

    /**
     * Be sure to specify the name of your application. If the application name
     * is {@code null} or blank, the application will log a warning. Suggested
     * format is "MyCompany-ProductName/1.0".
     */
    private static final String APPLICATION_NAME = "AdWords.MerchantCenterProxy";

    /** Global instance of the HTTP transport. */
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = new JacksonFactory();

    private static final String SERVICE_ACCOUNT_EMAIL = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX@developer.gserviceaccount.com";
    
    private static final String SERVICE_ACCOUNT_USER = "XXXXXXXXXXXXXXXXXXXX@gmail.com";
    
    private static final BigInteger merchantId = new BigInteger("123456789");

    /** Authorizes the installed application to access user's protected data. */
    private static Credential authorize() throws Exception {
        String p12FilePath = System.getProperty("user.dir") + "\\XXXXXXXXXX.p12";
        GoogleCredential credential = new GoogleCredential.Builder()
                .setTransport(HTTP_TRANSPORT)
                .setServiceAccountPrivateKeyFromP12File(new File(p12FilePath))
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
                .setServiceAccountScopes(Collections.singleton(ShoppingContentScopes.CONTENT))
                .setServiceAccountUser(SERVICE_ACCOUNT_USER)
                .build();
        credential.refreshToken();
        return credential;
    }
}

 

代碼說明:

注意到這一段:

        Properties systemProperties = System.getProperties();
        systemProperties.setProperty("http.proxyHost", "127.0.0.1");
        systemProperties.setProperty("http.proxyPort", "8087");
        systemProperties.setProperty("https.proxyHost", "127.0.0.1");
        systemProperties.setProperty("https.proxyPort", "8087");
        systemProperties.setProperty("socksProxyHost", "127.0.0.1");
        systemProperties.setProperty("socksProxyPort", "8087");

這是設置使用代理方式連接訪問google。

 

這句:

        System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(900000));// (單位:毫秒)

是指連接超時設置,當然了,也可以單獨使用我已經注釋的這段來做單個httprequest connection readtimeout設置:

//                .setHttpRequestInitializer(new HttpRequestInitializer() {
//                    public void initialize(HttpRequest httpRequest) throws IOException {
//                        httpRequest.setReadTimeout(90000000);
//                        credential.initialize(httpRequest);
//                    }
//                })

 

運行輸出結果:

 


 

 

最后附上.net的調用方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.GData.ContentForShopping;
using Google.GData.ContentForShopping.Elements;
using Google.GData.Client;
using Google.GData.Extensions;
using AdWords.Model;
using AdWords.Config;
using System.Xml;
using Google.Apis.Auth.OAuth2;
using Google.Apis.ShoppingContent.v2;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Services;


namespace AdWords.MerchantCenterProxy
{
    public class MerchantHelper
    {
        /// <summary>
        /// Merchant Account ID
        /// </summary>
        public static ulong MerchantCenterAccountId { get { return ulong.Parse(System.Configuration.ConfigurationManager.AppSettings["MerchantCenterAccountId"]); } }

        /// <summary>
        /// 登陸狀態
        /// </summary>
        private static ServiceAccountCredential credential;

        /// <summary>
        /// 取得Google API OAuth2登陸狀態
        /// </summary>
        /// <returns></returns>
        public static ServiceAccountCredential GetCredential()
        {
            if (credential == null)
            {
                String serviceAccountEmail = System.Configuration.ConfigurationManager.AppSettings["GoogleApiAccountEmail"];
                String certificateFilePath = System.Configuration.ConfigurationManager.AppSettings["GoogleApiCertificateFilePath"];
                String MerchantCenteruUser = System.Configuration.ConfigurationManager.AppSettings["MerchantCenterUserName"];

                var certificate = new X509Certificate2(certificateFilePath, "notasecret", X509KeyStorageFlags.Exportable);
                credential = new ServiceAccountCredential(
                   new ServiceAccountCredential.Initializer(serviceAccountEmail)
                   {
                       User = MerchantCenteruUser,
                       Scopes = new[] { ShoppingContentService.Scope.Content }
                   }.FromCertificate(certificate));
            }

            return credential;
        }

        /// <summary>
        /// 取得ShoppingContent Service
        /// </summary>
        /// <returns></returns>
        public static ShoppingContentService GenerateShoppingContentService()
        {
            var service = new ShoppingContentService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = GetCredential(),
                ApplicationName = "AdWords.MerchantCenterProxy",
            });
            return service;
        }
    }
}

.net的Google API的dll下載,可以使用Package Manager Console中使用install命令下載得到。具體上網搜索一下即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM