我想在 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"
我只知道如何通过传递 JSON
对象来发出简单的 POST
请求,但我从未尝试过基于 POST
在 curl
命令之上。
这是我根据此 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
这是我如何使用 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;
}
}
我发现这很有用 link但我无法真正理解如何在我的示例中使用它。
它和我的例子有什么不同吗?如果是,我如何POST
以下数据?
注意:所需数据
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
这是 API 的完整文档
最佳答案
您的 HttpURLConnection 需要三样东西:
- 请求方法。您可以使用 setRequestMethod 进行设置.
- 标题。您可以使用 setRequestProperty 设置它们.
- 内容类型。 The HTML specification requires包含表单提交的 HTTP 请求将
application/x-www-form-urlencoded
(或multipart/form-data
)作为其主体的内容类型。这是通过使用setRequestProperty
方法设置Content-Type
header 来完成的,就像其他 header 一样。
不清楚您要在这里做什么。正如 Boris Verkhovskiy 指出的那样,curl 的 --form
选项将数据作为多部分请求的一部分包含在内。在您的命令中,该请求的内容将是 URL 本身的字符。如果您真的想提交 URL,而不是这些位置的图像,您可以使用 application/x-www-form-urlencoded
请求正文来执行此操作。正文本身需要进行 URL 编码,如内容类型所示。 URLEncoder class为此目的而存在。
步骤如下:
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);
}
但是,如果您想提交实际图像,则需要创建一个 MIME 请求正文。 Java SE 不能这样做,但是 MimeMultipart类JavaMail ,它是 Java EE 规范的一部分,可以。
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);
}
您应该从代码中删除所有 catch
block ,并修改您的方法签名以包含 throws IOException
(或 throws IOException, MessagingException
) .您不希望您的应用程序的用户在操作失败时认为操作成功,对吧?
关于java - 如何使用 java 将 curl 命令转换为 HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57626667/