2016-03-10 42 views
0

我需要發送參數curl request但我沒有關於捲曲請求。如何用java發送捲曲

請求是:如何發送它在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 
+4

Cann你告訴我們爲什麼你想在Java中使用cURL?那裏有數千個圖書館。 – PatrickMA

+0

我不知道。這是第三方API我只需要通過幾個參數 –

+0

我已經開發了我的網絡應用程序在Java –

回答

1

如果我正確地理解了你,你想要使用API​​,並且有人給了你curl命令作爲例子如何做。

你現在想要在你的JAVA程序中實現相同的功能。

有幾個庫可以讓你實現這個目標。 Google for«java http client post»。

Sending HTTP POST Request In JavaHTTP 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(); 
} 
+0

thanx你這麼多我正在嘗試它 –

2

嗯,有這樣做的更好的方法,但如果由於某種原因,你真的想用捲曲,

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函數在終端中運行一個命令,所以你可以執行你的請求。

也就是說,對於發佈或放置請求。爲了獲得,只需讀取它的輸出。

http://000.00.00.00:8080/api

如果要發送請求,而無需在客戶端系統上安裝捲曲的可執行文件,看的Apache HttpClient庫。 :)

+0

你可以請解釋一下 –

+0

我想發佈請求,請你能分享代碼如何實現我的curl請求 –

+0

MY curl request is:curl --user xxx:xxxpass -H「Content-Type:application/json」-X POST -d '{「ImageId」:「local」, 「ImageUrl」:「http:// www。 gapicanada.ca/products/res/thumbimg/classic-fit-and-flare-dress-modern-red.jpg「}' http://000.00.00.00:8080/api –