我的应用程序在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时我们需要传递GoogleCredentialHttpRequestFactory 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(...);
    });

换句话说,当创建新请求时,凭据可以设置标头等,然后您还可以设置读取超时。

07-24 09:34