我的应用程序在GAE中运行。此应用程序将休息呼叫我的CloudMl。
这是该
的代码GoogleCredential credential = GoogleCredential.getApplicationDefault()
.createScoped(Collections.singleton(CLOUDML_SCOPE));
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(
credential);
GenericUrl url = new GenericUrl(cloudMLRestUrl);
JacksonFactory jacksonFactory = new JacksonFactory();
JsonHttpContent jsonHttpContent = new JsonHttpContent(jacksonFactory, getPayLoad());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
jsonHttpContent.setWrapperKey("instances");
jsonHttpContent.writeTo(baos);
LOG.info("Executing request... " + baos.toString());
HttpRequest request = requestFactory.buildPostRequest(url, jsonHttpContent);
HttpResponse response = request.execute();
通常会导致ReadTimeout异常导致上述代码。
java.net.SocketTimeoutException: Read timed out at
java.net.SocketInputStream.socketRead0(Native Method) ~[na:1.8.0_121] at
java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
~[na:1.8.0_121] at
java.net.SocketInputStream.read(SocketInputStream.java:171) ~[na:1.8.0_121]
at
似乎我们可以使用自定义超时添加httprequestinitializer,但是我们需要在创建httprequestfactory时通过googlecredential HttpRequestFactory requestFactory = httpTransport.createRequestFactory(GoogleCredential);
因此,我不能使用自定义的httprequestinitializer。如何增加使用Googlecredential httprequestinitializer创建的httprequestFactory的ReadTimeout?
我还没有尝试过,但是我希望您能够有效地将请求初始化器链接在一起:
final GoogleCredential credential = ...;
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(
new HttpRequestInitializer() {
@Override public void initialize(HttpRequest request) {
credential.initialize(request);
request.setReadTimeout(...);
}
});
或作为lambda表达式:
final GoogleCredential credential = ...;
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(
request -> {
credential.initialize(request);
request.setReadTimeout(...);
});
换句话说,当创建新请求时,凭据能够设置标题等,然后还设置了读取超时。