我使用Java客户机中的rest模板登录到服务器,并接收所需的标头,以升级到安全websocket的连接。
这是我的代码:
private static void loginAndSaveJsessionIdCookie(final String user, final String password, final HttpHeaders headersToUpdate) {
String url = "http://localhost:" + port + "/websocket-services/login.html";
new RestTemplate().execute(url, HttpMethod.POST,
new RequestCallback() {
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
System.out.println("start login attempt");
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("username", user);
map.add("password", password);
new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
}
},
new ResponseExtractor<Object>() {
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
System.out.println("got login repsonse");
headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
return null;
}
});
}这通常有效,但偶尔(特别是在websocket连接超时之后)服务器没有响应,我的客户端在方法挂起等待响应时停止响应。
有人能提出解决办法或为此而努力吗?因为它会导致客户完全冻结,需要一个强制关闭。
发布于 2015-09-21 09:23:01
要异步任何代码线程都是最好的方法,您可以使用ExecutorService来指定您想要的任何超时。根据您的需要(请参阅chk API以了解它们之间的差异) :-
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;或
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;https://stackoverflow.com/questions/32690886
复制相似问题