3

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": "smth@domain.com", "emailTo": 
["smth@gmail.com"], "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

Phill Alexakis
  • 1,449
  • 1
  • 12
  • 31

2 Answers2

3

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?

VGR
  • 40,506
  • 4
  • 48
  • 63
0
`    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class CurlToJavaExample {
public static void main(String[] args) {
    try {
        // Set the cURL command from Postman
        String curlCommand ="request";

        // Extract the URL
        String url = curlCommand.split("'")[1];

        // Create a URL object with the target URL
        URL apiUrl = new URL(url);

        // Open a connection to the URL
        HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

        // Set the request method to POST
        connection.setRequestMethod(curlCommand.split("--request")[1].split("'")[0].trim());

        // Extract headers from the cURL command
        String[] headers = curlCommand.split("--header ");
        for (int i = 1; i < headers.length; i++) {
            String header = headers[i].trim().split("'")[1];
            String[] keyValue = header.split(": ");
            connection.setRequestProperty(keyValue[0], keyValue[1]);
        }

        // Extract the request body from the cURL command
        String requestBody = curlCommand.split("--data-raw ")[1].trim().split("'")[1];

        // Set the request body
        connection.setDoOutput(true);
        connection.getOutputStream().write(requestBody.getBytes("UTF-8"));

        // Get the response code
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        // Read the response
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // Print the response
        System.out.println("Response: " + response.toString());

        // Close the connection
        connection.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

`

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – alea Jun 08 '23 at 12:58