简体   繁体   English

如何使用 java 将 curl 命令转换为 HTTP POST 请求

[英]How to transform a curl command to HTTP POST request using java

I would like to run this specific curl command with a HTTP POST request in java我想在java使用HTTP POST请求运行这个特定的 curl 命令

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.我只知道如何通过传递JSON对象来发出简单的POST请求,但我从未尝试过基于上述curl命令进行POST

Here is a POST example that I've made based on this curl command:这是我基于此curl命令制作的POST示例:

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这是我如何使用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?如果是我怎样才能POST以下数据?

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这是API的完整文档

There are four things that your HttpURLConnection needs:您的 HttpURLConnection 需要四件事:

  • The request method.请求方法。 You can set this with setRequestMethod .您可以使用setRequestMethod进行设置。
  • The headers.标题。 You can set them with setRequestProperty .您可以使用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. HTML 规范要求包含表单提交的 HTTP 请求将application/x-www-form-urlencoded (或multipart/form-data )作为其正文的内容类型。 This is done by setting the Content-Type header using the setRequestProperty method, just like the other headers.这是通过使用setRequestProperty方法设置Content-Type标头来完成的,就像其他标头一样。
  • The body itself needs to URL-encoded, as the content type indicates.正如内容类型所指示的那样,正文本身需要进行 URL 编码。 The URLEncoder class exists for this purpose. URLEncoder 类就是为此目的而存在的。

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 .您应该从代码中删除所有catch块,并修改您的方法签名以包含throws IOException You don't want users of your application to think the operation was successful if in fact it failed, right?你不希望你的应用程序的用户认为操作成功了,如果实际上它失败了,对吧?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM