我在 Java 客户端中使用 Rest 模板来登录服务器并接收所需的 header ,以将连接升级到安全 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 连接超时后)服务器没有响应,并且我的客户端在方法挂起等待响应时停止响应。
有人可以建议修复或解决此问题吗?因为它会导致客户端完全卡住,需要强制关闭。
最佳答案
异步任何代码线程是最好的方法,您可以使用 ExecutorService 指定您希望的任何超时。根据您的需要,可以使用以下两个选项(请检查 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;
关于java - Spring RestTemplate - 登录请求有时会挂起等待响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32690886/