我想知道是否有机会使用类似Google API Java客户端的东西来为应用程序创建自定义客户端,而不是从头开始。
我将使用Google App Engine来运行它,如果在使用某些东西方面有优势,它会突然出现在我的脑海中。#34;触及"谷歌手。
你有没有试过这样的东西?
答案 0 :(得分: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);
}
}
}
此时您可以像使用其他Google 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();
那就是它!