我的应用程序在 GAE 中运行。此应用程序对我的 CloudML 进行 REST 调用。
这是代码
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?