Reputation:
I need to connect to a web application, which performs an HTTP redirect if the requested url is not mapped within the app. (for example: /users -> /users/) For authentication we use a token-based approach, so I have to send a token with each request.
I always get an java.lang.IllegalStateException: Already connected
, when I set the token after a redirect. Can somebody help me with this problem?
Here is what I did:
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;
}
Upvotes: 1
Views: 491
Reputation: 1883
I think you should be setting connection.setInstanceFollowRedirects(true)
which will make the connection follow HTTP redirects then remove
// has the request been redirected?
if (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
String newUrl = connection.getHeaderField("Location");
connection = (HttpURLConnection) new URL(ENDPOINT + newUrl).openConnection();
I can't see from your code why you needed to set setInstanceFollowRedirects
to false
Upvotes: 1