2016-11-23 304 views
-1

我能找到一些解決方案,但沒有人爲我工作。我是Java新手,迄今爲止在Java中使用curl還沒有成功。curl命令如何轉換爲Java代碼?

curl -X POST -H "Content-Type: application/json" -o output.json --data-binary @input.json http://webaddress.com 

JSON文件。

{ 
    "firstNumber": "00", 
    "secondNumber": "12", 
    "Type": "MyType", 
    "data": [0,0,0,0,0] 
} 

任何幫助將非常感激。

+1

你是什麼意思,它是如何翻譯? – Carcigenicate

+1

你問如何從java啓動curl或如何複製curl在java中的功能? – bradimus

+3

[將curl調用轉換爲java urlconnection調用]可能重複(http://stackoverflow.com/questions/15684846/convert-curl-call-into-java-urlconnection-call) –

回答

0

最簡單的方法是從Java調用命令:

Process proc = 
    run.exec(new String[] { 
    "/bin/sh", 
    "-c", 
    "curl -X POST -H 'Content-Type: application/json' -o output.json --data-binary @input.json http://webaddress.com" 
    }); 

/bin/sh是你的shell的位置。 -c之後執行命令。

當然,如果你的shell路徑將保持不變,你可以將你的命令移動到某種字符串常量,也可以提取執行命令的實用程序方法。

0

我已經與Spring的RestTemplate很好的經驗,這裏有一個例子:

JSONObject request = new JSONObject(); 
request.put("attribute1", "value"); 
request.put("attribute2", "value2"); 

RestTemplate restTemplate=new RestTemplate(); 
HttpHeaders headers = new HttpHeaders(); 
headers.setContentType(MediaType.APPLICATION_JSON); 
HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers); 

ResponseEntity<String> loginResponse = restTemplate.exchange(urlString, HttpMethod.POST, entity, String.class); 
+0

感謝您的回覆,這看起來像一個字符串正在發送。我將如何改變這個使用curl命令中的--data-binary。 – konopoly

+0

如果文件包含原始Json,您將讀取該文件並將其轉換爲字符串。 –