我正在写一个java方法来向我们的一个端点发送一个post请求,该方法需要担心的是发送请求,但不关心端点是否收到了请求(fire and forget)。
我如何用HttpUrlConnection实现这个功能?
我有下面的内容,但我不确定发射connection.disconnect();是否是最佳实践?
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();
disconnect()
表示近期不太可能向服务器发出其他请求。
为了简单的向客户端发送消息,然后断开连接,我认为这是最安全的做法。请注意,调用 disconnect()
不应意味着 HttpURLConnection
实例可以重复使用于新的连接。