3

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?

st4hoo
  • 2,196
  • 17
  • 25
lovrodoe
  • 473
  • 8
  • 18

2 Answers2

3

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.

lovrodoe
  • 473
  • 8
  • 18
0

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.

Ragesh
  • 205
  • 3
  • 11
  • The thing is I didn't even establish a connection in the first place because I have yet to add a client certificate, so I'm not getting past the handshake. I never called connection.connect() either. – lovrodoe Sep 20 '18 at 12:23
  • You no need to call connect() because you are using getInputStream() Check this link: https://docs.oracle.com/javase/tutorial/networking/urls/connecting.html – Ragesh Sep 20 '18 at 12:32
  • 1
    Thanks, input stream may have been the issue. – lovrodoe Sep 20 '18 at 12:37
  • You are welcome. If the answer was correct just tick it to help others. – Ragesh Sep 20 '18 at 12:45