Home > Back-end >  Java 11 sending HTTP post request without body
Java 11 sending HTTP post request without body

Time:02-12

I am using java 11 http client and I need to send a post request without body.

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

When I try as above I receive 411 error code. I also tried to set "Content-Length" header "0" but saw that is restricted.

Then I tried this:

    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();

It throws java.io.FileNotFoundException

Normally I should use response like below:

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

So how can I make this request?

CodePudding user response:

I achieved it with 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);

CodePudding user response:

You should be able to do the same with HttpClient - on Jdk 11 if I enable logging with -Djdk.httpclient.HttpClient.log=requests,headers I can see that Content-Length: 0 is sent with the following request:

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());
  • Related