如何在 Google HTTP 客户端中增加 ReadTimeout
Posted
技术标签:
【中文标题】如何在 Google HTTP 客户端中增加 ReadTimeout【英文标题】:How to increase ReadTimeout in Google HTTP Client 【发布时间】:2017-10-01 01:45:33 【问题描述】:我的应用程序在 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?
【问题讨论】:
【参考方案1】:我还没有尝试过,但我希望您能够有效地将请求初始化程序链接在一起:
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(...);
);
换句话说,当一个新请求被创建时,凭证可以设置标题等,然后你也可以设置读取超时。
【讨论】:
我使用了下面的 lamda 相当于上面的HttpRequestInitializer requestInitializer = request -> credential.initialize(request); request.setReadTimeout(0);; HttpRequestFactory requestFactory = httpTransport.createRequestFactory(requestInitializer);
@sag:当然 - 会在我的回答中添加它作为替代方案。以上是关于如何在 Google HTTP 客户端中增加 ReadTimeout的主要内容,如果未能解决你的问题,请参考以下文章
如何编辑 Google Cloud 任务的默认超时(使用 http 目标,而不是应用引擎)?
TypeError:不能在 re.findall() 中的类似字节的对象上使用字符串模式
Google 如何在 API 调用中验证 SHA1 和包名称?
如何在没有 Oauth 的情况下访问 Google 客户端 API(仅 API 密钥)