I am writing a java method to fire a post request to one of our endpoints. All the method needs to worry about is sending the request, but not being concerned if the endpoint has received it (fire and forget).
How would I achieve this with HttpUrlConnection?
I have the following but i'm unsure if firing connection.disconnect(); is best practice?
HttpURLConnection connection = (HttpURLConnection) EndpointUrl.openConnection();
// Set the http rest call to POST.
connection.setRequestMethod("POST");
// Set the request properties, including the Authorization tag.
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", header);
connection.setDoOutput(true);
ObjectMapper mapper = new ObjectMapper();
try(OutputStream outputStream = connection.getOutputStream()) {
byte[] input = mapper.writeValueAsBytes(log);
outputStream.write(input, 0, input.length);
}
connection.disconnect();
From docs.oracle.com:
disconnect()
Indicates that other requests to the server are unlikely in the near future.
For the sake of simply sending a message to the client and then disconnecting, I think this is the safest practice. Note that calling disconnect()
should not imply that the HttpURLConnection
instance can be reused for new connections.