Search code examples
javahttprequesthttpurlconnectionnshttpurlresponse

How can I call HttpUrlConnection disconnect()


My code sends HttpConnection and then tries to use either connection.getInputStream() or connection.getErrorStream() to deserialize response.

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); // getErrorStream()
String content = in.lines().collect(Collectors.joining());

How can I pass connection to parse(HttpURLConnection connection) function and call connection.disconnect() after it's finished()?

I was thinking about

connection.disconnect();
return MyObject.fromString(connection.getInputStream(), connection.getErrorStream());

but not sure whether it makes sense to disconnect before reading the response.


Solution

  • You can do something like this:

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    String content = parse(connection);
    connection.disconnect();
    // do something with content