如何关闭HttpsURLConnection Java

时间:2018-10-06 23:25:04

标签: java https

我正在尝试使用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

2 个答案:

答案 0 :(得分:1)

  

java.lang.IllegalStateException:已连接

该异常表示您已尝试设置属性,该属性为请求发送后赋予授权

这可能是发生这种情况的地方:

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

Auth呼叫setRequestProperty

如果尚未发送请求,则请求响应代码将导致发送请求。 (很明显……直到获得响应,您才能获得响应代码,除非发送请求,否则服务器无法给您一个响应代码。)


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

但这不是导致您出现问题的原因。 stacktrace清楚地表明,有人在调用setRequestProperty时发生了异常。

答案 1 :(得分:0)

根据Stephen C的回答,我确定了交换顺序:

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

因此可行的解决方案是:

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

我假设ResponseCode()向服务器创建请求(如果尚未发出请求),否则ResponseCode()使用预先存在的请求。经过进一步测试,我得出结论,不需要致电.disconnect()

相关问题