Java 11 发送 HTTP post 请求而不 body

Java 11 sending HTTP post request without body

我正在使用 java 11 http 客户端,我需要发送 post 没有 body 的请求。

HttpRequest request = getRequestBuilder()
    .uri(urlBuilder.toURL().toURI())
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); 

当我尝试上述操作时,我收到 411 错误代码。 我还尝试设置“Content-Length”header“0”,但看到它受到限制。

然后我试了这个:

    URL url = new URL(getHost());
    Map<String,Object> params = new LinkedHashMap<>();
    params.put("trackingNo", orderPackage.getCargoTrackingCode());
    params.put("referenceNo", orderPackage.getCargoCode());

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String,Object> param : params.entrySet()) {
        if (postData.length() != 0) postData.append('&');
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    byte[] postDataBytes = postData.toString().getBytes("UTF-8");

    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    StringBuilder sb = new StringBuilder();
    for (int c; (c = in.read()) >= 0;)
        sb.append((char)c);
    String response = sb.toString();

它抛出 java.io.FileNotFoundException

通常我应该使用如下响应:

CancelDeliveryResponse cancelDeliveryResponse = gson.fromJson(httpResponse.body(), CancelDeliveryResponse.class);

那么我该如何提出这个请求呢?

我用 HttpURLConnection 实现了它:

HttpURLConnection con = (HttpURLConnection) urlBuilder.toURL().openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Authorization", "Bearer " + getCargoApiAuthToken());
con.setFixedLengthStreamingMode(0);
con.connect();

if (con.getResponseCode() != 200 && con.getResponseCode() != 201) {
    // Error response scenario
    return;
}

BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

StringBuilder stringBuilder = new StringBuilder();

String line;
while ((line = reader.readLine()) != null) {
    stringBuilder.append(line).append("\n");
}

CancelDeliveryResponse cancelDeliveryResponse = gson.fromJson(stringBuilder.toString(), CancelDeliveryResponse.class);

您应该可以对 HttpClient 执行相同的操作 - 在 Jdk 11 上,如果我使用 -Djdk.httpclient.HttpClient.log=requests,headers 启用日志记录,我可以看到 Content-Length: 0 随以下请求一起发送:

HttpRequest request = HttpRequest.newBuilder()
    .uri(<uri>)
    .header("Authorization", "Bearer " + <token>)
    .version(HttpClient.Version.HTTP_1_1)
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());