How can I call HttpUrlConnection disconnect()

134 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

You can do something like this:

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