我需要连接到一个Web应用程序,如果请求的URL未在应用程序中映射,则执行HTTP重定向。 (例如:/ users - > / users /)对于身份验证,我们使用基于令牌的方法,因此我必须为每个请求发送一个令牌。
当我在重定向后设置令牌时,我总是得到java.lang.IllegalStateException: Already connected
。有人可以帮我解决这个问题吗?
这是我做的:
try {
// setup connection
URL url = new URL(ENDPOINT + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method.toString().toUpperCase());
connection.setInstanceFollowRedirects(false);
// has the request been redirected?
if (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
String newUrl = connection.getHeaderField("Location");
connection = (HttpURLConnection) new URL(ENDPOINT + newUrl).openConnection();
}
if (useToken) {
connection.addRequestProperty("Authorization", testToken);
}
// post data
if (data != null) {
connection.setDoOutput(true);
connection.addRequestProperty("Content-Type", "application/json");
String json = new Gson().toJson(data);
try (OutputStream dataStream = connection.getOutputStream()) {
dataStream.write(json.getBytes());
}
}
// retrieve response
String body = IOUtils.toString(connection.getInputStream());
return new TestResponse(connection.getResponseCode(), body);
} catch (IOException ex) {
LOGGER.error(ex.getMessage());
return null;
}
答案 0 :(得分:1)
我认为你应该设置connection.setInstanceFollowRedirects(true)
,这将使连接遵循HTTP重定向然后删除
// has the request been redirected?
if (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
String newUrl = connection.getHeaderField("Location");
connection = (HttpURLConnection) new URL(ENDPOINT + newUrl).openConnection();
我无法从您的代码中看到为什么需要将setInstanceFollowRedirects
设置为false