我想知道是否有机会使用 Google API Java 客户端之类的东西为应用程序制作自定义客户端,而不是从头开始。
我将使用 Google App Engine 来运行它,所以如果使用 Google Hands“触摸”的东西有优势的话,它就会突然出现在我的脑海中。
你试过这样的事情吗?
最佳答案
长话短说
是的!
正如@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();
就是这样!
关于java - 是否可以使用适用于 Java 的 Google API 客户端库创建自定义客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33409271/