我的应用程序在GAE中运行。此应用程序使REST调用我的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?
答案 0 :(得分:4)
我还没有尝试过,但我希望您能够将请求初始化程序有效地链接在一起:
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(...);
});
换句话说,当创建新请求时,凭证可以设置标题等,然后您也可以设置读取超时。