Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a curl command to HTTP POST request using java

Tags:

java

curl

I would like to run this specific curl command with a HTTP POST request in java

curl --location --request POST "http://106.51.58.118:5000/compare_faces?face_det=1" \
  --header "user_id: myid" \
  --header "user_key: thekey" \
  --form "img_1=https://cdn.dnaindia.com/sites/default/files/styles/full/public/2018/03/08/658858-577200-katrina-kaif-052217.jpg" \
  --form "img_2=https://cdn.somethinghaute.com/wp-content/uploads/2018/07/katrina-kaif.jpg"

I only know how to make simple POST requests by passing a JSON object, But i've never tried to POST based on the above curl command.

Here is a POST example that I've made based on this curl command:

curl -X POST TheUrl/sendEmail 
-H 'Accept: application/json' -H 'Content-Type: application/json' 
-d '{"emailFrom": "[email protected]", "emailTo": 
["[email protected]"], "emailSubject": "Test email", "emailBody":
"708568", "generateQRcode": true}' -k 

Here is how i did it using java

    public void sendEmail(String url) {
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");
            con.setDoOutput(true);

            // Send post request
            JSONObject test = new JSONObject();
            test.put("emailFrom", emailFrom);
            test.put("emailTo", emailTo);
            test.put("emailSubject", emailSubject);
            test.put("emailBody", emailBody);
            test.put("generateQRcode", generateQRcode);
            String jsonInputString = test.toString();
            System.out.println(jsonInputString);
            System.out.println("Email Response:" + returnResponse(con, jsonInputString));
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("Mail sent");
    }

    public String returnResponse(HttpURLConnection con, String jsonInputString) {
        try (OutputStream os = con.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("utf-8");
            os.write(input, 0, input.length);
        } catch (Exception e) {
            System.out.println(e);
        }
        try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
            StringBuilder response = new StringBuilder();
            String responseLine = null;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            return response.toString();
        } catch (Exception e) {
            System.out.println("Couldnt read response from URL");
            System.out.println(e);
            return null;
        }
    }

I've found this useful link but i can't really understand how to use it in my example.

Is it any different from my example? and if yes how can i POST the following data?

Note: Required Data


HEADERS:

user_id myid
user_key mykey

PARAMS:
face_det 1
boxes 120,150,200,250 (this is optional)


BODY:

img_1
multipart/base64 encoded image or remote url of image

img_2
multipart/base64 encoded image or remote url of image

Here is the complete documentation of the API

like image 877
Phill Alexakis Avatar asked Jul 23 '26 20:07

Phill Alexakis


1 Answers

There are three things that your HttpURLConnection needs:

  • The request method. You can set this with setRequestMethod.
  • The headers. You can set them with setRequestProperty.
  • The content type. The HTML specification requires that an HTTP request containing a form submission have application/x-www-form-urlencoded (or multipart/form-data) as its body’s content type. This is done by setting the Content-Type header using the setRequestProperty method, just like the other headers.

It’s not clear what you’re trying to do here. As Boris Verkhovskiy points out, curl’s --form option includes data as a part of a multipart request. In your command, the content of that request would be the characters of the URLs themselves. If you really want to submit URLs, not the images at those locations, you could use an application/x-www-form-urlencoded request body to do it. The body itself needs to URL-encoded, as the content type indicates. The URLEncoder class exists for this purpose.

The steps look like this:

String img1 = "https://cdn.dnaindia.com/sites/default/files/styles/full/public/2018/03/08/658858-577200-katrina-kaif-052217.jpg";
String img2 = "https://cdn.somethinghaute.com/wp-content/uploads/2018/07/katrina-kaif.jpg";

con.setRequestMethod("POST");
con.setDoOutput(true);

con.setRequestProperty("user_id", myid);
con.setRequestProperty("user_key", thekey);

con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

String body = 
    "img_1=" + URLEncoder.encode(img1, "UTF-8") + "&" +
    "img_2=" + URLEncoder.encode(img2, "UTF-8");

try (OutputStream os = con.getOutputStream()) {
    byte[] input = body.getBytes(StandardCharsets.UTF_8);
    os.write(input);
}

However, if you want to submit the actual images, you will need to create a MIME request body. Java SE cannot do this, but the MimeMultipart class of JavaMail, which is part of the Java EE specification, can.

Multipart multipart = new MimeMultipart("form-data");
BodyPart part;
part = new MimeBodyPart();
part.setDataHandler(new DataHandler(new URL(img1)));
multipart.addBodyPart(part);
part = new MimeBodyPart();
part.setDataHandler(new DataHandler(new URL(img2)));
multipart.addBodyPart(part);

con.setRequestMethod("POST");
con.setDoOutput(true);

con.setRequestProperty("user_id", myid);
con.setRequestProperty("user_key", thekey);

con.setRequestProperty("Content-Type", multipart.getContentType());

try (OutputStream os = con.getOutputStream()) {
    multipart.writeTo(os);
}

You should remove all catch blocks from your code, and amend your method signatures to include throws IOException (or throws IOException, MessagingException). You don’t want users of your application to think the operation was successful if in fact it failed, right?

like image 183
VGR Avatar answered Jul 26 '26 11:07

VGR