【问题标题】:Send Post request to endpoint but ignore response向端点发送 Post 请求但忽略响应
【发布时间】:2020-09-30 23:28:56
【问题描述】:

我正在编写一个 java 方法来向我们的一个端点发出一个 post 请求。 所有方法需要担心的是发送请求,但不关心端点是否收到它(即发即弃)。

如何使用 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();

【问题讨论】:

标签: java rest httpurlconnection


【解决方案1】:

来自docs.oracle.com

disconnect()

表示在不久的将来不太可能向服务器发出其他请求。

为了简单地向客户端发送消息然后断开连接,我认为这是最安全的做法。请注意,调用disconnect() 不应暗示HttpURLConnection 实例可用于新连接。

【讨论】:

    猜你喜欢
    • 2020-07-29
    • 1970-01-01
    • 2012-05-13
    • 2017-03-01
    • 2019-07-12
    • 2019-09-29
    • 1970-01-01
    • 2021-11-17
    • 2019-09-08
    相关资源
    最近更新 更多