gpt4 book ai didi

java - HttpURL连接 : Already connected after redirect

转载 作者:行者123 更新时间:2023-11-30 06:45:30 25 4
gpt4 key购买 nike

我需要连接到一个 Web 应用程序,如果请求的 URL 未在应用程序内映射,该应用程序将执行 HTTP 重定向。 (例如:/users ->/users/)对于身份验证,我们使用基于 token 的方法,因此我必须在每个请求中发送一个 token 。

当我在重定向后设置 token 时,我总是收到 java.lang.IllegalStateException: Already connect 。有人可以帮我解决这个问题吗?

这是我所做的:

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;
}

最佳答案

我认为您应该设置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

关于java - HttpURL连接 : Already connected after redirect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43744505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com