How to send curl with java

I need to send parameter in curl request but i don't about curl request.

Request is: How to send it in 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

Well, there are better ways of doing this, but if for some reason you really want to use 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"}'"

Essentially, this Java function runs a command in terminal, so you can execute your request.

That is, for a post or put request. For get, just read it's output.

http://000.00.00.00:8080/api

If you want to send the request without having to install curl executables on the client system, look at Apache HttpClient library. :)


If I understand you correctly, you want to consume the API and somebody gave you the curl command as an example how to do so.

You now want to achieve the same in your JAVA program.

There are a few libraries which allow you to achieve this. Google for «java http client post».

Sending HTTP POST Request In Java or HTTP POST using JSON in Java answers this is as well.

In your case this would be something like:

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();
}
链接地址: http://www.djcxy.com/p/45854.html

上一篇: 在JAVA中使用JSON字符串的HTTP POST请求

下一篇: 如何用java发送curl