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

Phill Alexakis :

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

VGR :

There are four 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.
  • The body itself needs to URL-encoded, as the content type indicates. The URLEncoder class exists for this purpose.

Those four 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);
}

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=154140&siteId=1