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?