1

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.

B. Wasnie
  • 541
  • 1
  • 4
  • 12

1 Answers1

2

You can do something like this:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
String content = parse(connection);
connection.disconnect();
// do something with content
Victor P
  • 1,496
  • 17
  • 29