如何在 Google HTTP 客户端中增加 ReadTimeout

How to increase ReadTimeout in Google HTTP Client

我在 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?

我还没有试过这个,但我希望你能够有效地将请求初始值设定项链接在一起:

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(...);
    });

换句话说,当创建一个新的请求时,凭据可以设置headers等,然后你也可以设置读取超时。