我正在尝试使用HttpsURLConnection
从服务器请求数据;我当前的服务器要求用户通过提示输入用户名和密码。在web浏览器中,当您输入正确的用户名和密码后,浏览器会将用户名和密码保存为浏览器中的会话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
发布于 2018-10-07 08:37:34
根据Stephen C的回答,我确定了交换的顺序:
int responseCode = con.getResponseCode();
Auth(con);
因此,可行的解决方案是:
Auth(con);
int responseCode = con.getResponseCode();
我假设如果还没有发出请求,ResponseCode()
会创建一个到服务器的请求,否则ResponseCode()
会使用预先存在的请求。经过进一步的测试,我得出结论,没有必要调用.disconnect()
。
https://stackoverflow.com/questions/52684177
复制相似问题