2015-10-29 87 views
3

我想知道是否有機會使用類似Google API Java Client的東西爲應用程序創建自定義客戶端,而不是從頭開始。是否可以使用適用於Java的Google API客戶端庫創建自定義客戶端?

我打算使用Google App Engine來運行它,因此如果使用Google Hands「感動」的某些優勢時它會突然出現在我的頭上。

你有沒有嘗試過這樣的事情?

+1

你可以提供更多關於*完全*你的意思是「定製客戶端」的細節嗎? 「我要使用Google App Engine來運行它」是什麼意思? - 究竟運行什麼?如果你可以讓你的問題更清楚,幫助你會容易得多。 –

+1

「google api java client」是一個lib,一個標準的jar,你可以在這個 –

回答

3

TL; DR

YES!

正如@ igor-artamonov所說,您可以在適用於Java的Google API客戶端庫之上構建自定義REST Java客戶端。

你可以找到解釋和HubSpot API全樣本這裏:

http://in.shangrila.farm/java-client-for-hubspot-api-built-on-top-of-google-api-client-for-java

如何

首先,我假設你使用Maven,在這種情況下,你需要聲明這dep

<dependency> 
    <groupId>com.google.api-client</groupId> 
    <artifactId>google-api-client</artifactId> 
    <version>1.20.0</version> 
</dependency> 

然後您將創建REST客戶端類

public class YourOwnClient extends AbstractGoogleJsonClient { 

    public static final String DEFAULT_ROOT_URL = "https://your.api.com"; 
    public static final String DEFAULT_SERVICE_PATH = ""; 
    public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; 

    [... required methods and constructor for AbstractGoogleJsonClient ...] 

    public class YourOwnEndpoint { 
     public Get get() throws java.io.IOException { 
      Get result = new Get(); 
      initialize(result); 
      return result; 
     } 

     public class Get extends YourOwnClientRequest<your.own.api.model.Pojo> { 

      private static final String REST_PATH = "your/own/api/endpoint"; 

      protected Get() { 
       super(YourOwnClient.this, "GET", REST_PATH, null, your.own.api.model.Pojo.class); 
      } 
     } 
    } 

    public static final class Builder 
      extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { 
     public Builder(com.google.api.client.http.HttpTransport transport, 
       com.google.api.client.json.JsonFactory jsonFactory, 
       com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { 
      super(transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer, false); 
     } 

     @Override 
     public YourOwnClient build() { 
      return new YourOwnClient(this); 
     } 
    } 
} 

在這一點上,你可以使用這個像其他的谷歌API客戶端

HttpTransport transport = new ApacheHttpTransport(); 
JsonFactory jsonFactory = new GsonFactory(); 
HttpRequestInitializer httpRequestInitializer = new BasicAuthentication("usr", "pwd"); 

YourOwnClient client = new YourOwnClient.Builder(transport, jsonFactory, httpRequestInitializer).build(); 

your.own.api.model.Pojo pojo = client.YourOwnEndpoint().get().execute(); 

這就是它!

+0

之上構建任何你想要的東西,在服務器上編寫一個自定義客戶端是個好主意嗎?我問的原因是服務器代碼發生變化時,您需要非常密切地跟蹤它。同樣的事實,如果服務消費者碰到新的客戶端SDK,那麼它高度確信它對新服務器有效。 (假設服務器代碼在一段時間內可能不兼容......) –

+0

@BalajiBoggaramRamanarayan你知道你是對的,如果有一個官方的Java客戶端,我會使用它,但實際上並不存在:D – aqquadro

相關問題