【问题标题】:How to send curl with java [closed]如何用java发送curl [关闭]
【发布时间】:2016-03-10 06:11:02
【问题描述】:

我需要在curl request 中发送参数,但我不关心 curl 请求。

请求是:如何在java中发送。

curl --user xxx:xxxpass-H "Content-Type: application/json" -X POST -d
'{"ImageId":"local",
  "ImageUrl":"http://www.gapcanada.ca/products/res/thumbimg/classic-fit-and-flare-dress-modern-red.jpg"}'

http://000.00.00.00:8080/api

【问题讨论】:

  • 您能告诉我们为什么要在 Java 中使用 cURL 吗?那里有成千上万的图书馆。
  • 我不知道。这是第三方 api 我只需要传递几个参数
  • 我用 java 开发了我的网络应用程序
  • 你能在我的 curl 请求中分享代码吗?因为我没有得到如何用这个例子来实现我的请求

标签: java curl


【解决方案1】:

如果我对您的理解正确,您想使用 API,并且有人给了您 curl 命令作为示例如何使用该 API。

您现在想在您的 JAVA 程序中实现相同的目标。

有一些库可以让您实现这一目标。 Google for «java http client post»。

Sending HTTP POST Request In Java 或者 HTTP POST using JSON in Java 回答这个也是。

在你的情况下,这将是这样的:

JSONObject json = new JSONObject();
json.put("ImageId", "local");    
json.put("ImageUrl", "http://www.gapcanada.ca/products/res/thumbimg/classic-fit-and-flare-dress-modern-red.jpg");    

CloseableHttpClient httpClient = HttpClientBuilder.create().build();

try {
    HttpPost request = new HttpPost("http://000.00.00.00:8080/api");
    StringEntity params = new StringEntity(json.toString());
    request.addHeader("content-type", "application/json");
    request.setEntity(params);
    httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.close();
}

【讨论】:

  • 谢谢你,我正在尝试它
【解决方案2】:

嗯,有更好的方法可以做到这一点,但如果出于某种原因你真的想使用 curl,

Runtime.getRuntime.exec("curl --user xxx:xxxpass-H \"Content-Type: 
    application/json\" -X POST -d
    \'{\"ImageId\":\"local\",
    \"ImageUrl\":\"http://www.gapcanada.ca/products/res/thumbimg/classic-fit-and-flare-dress-modern-red.jpg\"}\'"

本质上,这个Java函数在终端中运行一个命令,所以你可以执行你的请求。

也就是说,对于 post 或 put 请求。对于获取,只需读取它的输出即可。

http://000.00.00.00:8080/api

如果您想发送请求而无需在客户端系统上安装 curl 可执行文件,请查看 Apache HttpClient 库。 :)

【讨论】:

  • 你能解释一下吗
  • 我正在尝试发布请求,请您分享如何实现我的 curl 请求的代码
  • 我的 curl 请求是: curl --user xxx:xxxpass -H "Content-Type: application/json" -X POST -d '{"ImageId":"local", "ImageUrl": "gapcanada.ca/products/res/thumbimg/…"}' 000.00.00.00:8080/api
  • @IrshadQureshi 更新了更多细节和您的要求。
  • 非常感谢你
猜你喜欢
  • 1970-01-01
  • 2011-01-15
  • 2010-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
相关资源
最近更新 更多