lovrodoe
lovrodoe

Reputation: 502

Java HTTP connection seems to remain open

I have created a connection in Java to private API

String urlRequest = "https://localhost:8080/orders/create";
String username = "test";
String password = "test";
String certificatePass = "test";
byte[] authEncBytes = Base64.getEncoder().encode((username + ":" + password).getBytes());

URL url = new URL(urlRequest);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + new   String(authEncBytes));
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");

conn.setDoOutput(true);
conn.setDoInput(true);

InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
is.close();

After the initial pass, connection seems to remain open, because when running the code from the start, HttpURLConnection throws an Exception at conn.setRequestMethod("POST");,

"Can't reset method: already connected"

I managed to somehow close it now, I don't know what have I done, but does anyone know what the issue here could have been? I restarted my PC in the meantime, and it would still thrown an exception at conn.setRequestMethod("POST");, I don't understand how can a connection persist between restarts. I also tried adding conn.disconnect() before trying to set request method, and that didn't seem to work either. The only thing that made a difference was changing the URL, but I could only connect once, every next time running the code would give me the same exception.

How do I close the connection properly?

Upvotes: 3

Views: 362

Answers (2)

lovrodoe
lovrodoe

Reputation: 502

Had the issue again today and the problem was with expressions in debug mode. I was calling connect there, I guess while testing so in case anyone didn't know, expressions do affect your variables and can change what's in memory. For instance, having:

int a = 5;
System.out.println(a);

in your code and having a = 6 in your Expressions list, System.out.println(a) will print 6, not 5.

Deleting expressions fixed my problem.

Upvotes: 3

Ragesh
Ragesh

Reputation: 215

I think your question already has an answer here.

Closing URLConnection and InputStream correctly?

Close your connection at end of the code and don't do it before setRequest method.

Upvotes: 0

Related Questions