gpt4 book ai didi

java - 如何关闭 HttpsURLConnection Java

转载 作者:行者123 更新时间:2023-12-02 10:44:32 27 4
gpt4 key购买 nike

我正在尝试使用HttpsURLConnection从服务器请求数据;我目前的服务器要求用户通过提示输入用户名和密码。在网络浏览器中,输入正确的用户名和密码后,浏览器会将用户名和密码保存为浏览器中的 session cookie,以便您可以访问网站内的其他页面,而不会提示您输入凭据。但对于Java客户端,它不保存用户名和密码。我尝试使用 .disconnect() 关闭连接,但我不断收到以下错误:

java.lang.IllegalStateException: Already connected
at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:3053)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.setRequestProperty(HttpsURLConnectionImpl.java:316)

我的Java代码:

private static void sendPost(String _url) throws Exception {

String url = _url;

URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

con.setRequestMethod("POST");

int responseCode = con.getResponseCode();
Auth(con);

if (responseCode == 200) {
label.setText("Sucssesfully Scanned: " + StudID.getText());
} else {
label.setText("Error, please scan again");
}
con.disconnect();
}

private static ArrayList<String> Get(String _url) throws Exception {
ArrayList<String> list = new ArrayList<>();
JsonParser parser = new JsonParser();

String url = _url;

URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Auth(con);

con.setRequestMethod("GET");

con.setRequestProperty("Accept", "application/json");

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}

in.close();
con.disconnect();

JsonElement element = parser.parse(response.toString());

if (element.isJsonObject()) {
JsonObject data = element.getAsJsonObject();
for (int i = 0; i < data.get("chapels").getAsJsonArray().size(); i++) {
JsonObject jObj = (JsonObject) data.get("chapels").getAsJsonArray().get(i);
list.add(jObj.get("Name").toString().replaceAll("\"", "") + " - " + jObj.get("Loc").toString().replaceAll("\"", ""));
}
}

return (list);
}
private static void Auth(HttpsURLConnection con){
String encodedBytes = Base64.getEncoder().encodeToString((BCrypt.hashpw("swheeler17", BCrypt.gensalt(10)) + ":" + BCrypt.hashpw("Trinity", BCrypt.gensalt(10))).getBytes());
con.setRequestProperty("authorization", "Basic " + encodedBytes);
}

用户名和密码提示示例:https://chapel-logs.herokuapp.com/chapel

最佳答案

java.lang.IllegalStateException: Already connected

该异常意味着您在发送请求后尝试设置为请求授权的属性。

这可能就是发生的地方:

    int responseCode = con.getResponseCode();
Auth(con);

Auth调用setRequestProperty

如果尚未发送,则请求响应代码会导致发送请求。 (显然......在收到响应之前你无法获得响应代码,并且除非发送请求,否则服务器无法给你响应代码。)

<小时/>

要回答您的问题,对连接调用 disconnect 将断开连接。

但这不是造成您问题的原因。堆栈跟踪清楚地表明异常是在调用 setRequestProperty 时发生的。

关于java - 如何关闭 HttpsURLConnection Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52684177/

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