2014-06-27 370 views
3

我需要將下面的curl命令轉換爲java命令。在java中將等同於下面的curl命令

$curl_handle = curl_init(); 

curl_setopt ($curl_handle, CURLOPT_URL,$url);`enter code here` 
curl_setopt ($curl_handle, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt ($curl_handle, CURLOPT_SSL_VERIFYPEER, 0); 
curl_setopt ($curl_handle, CURLOPT_POST, 1); 
curl_setopt ($curl_handle, CURLOPT_POSTFIELDS, $postfields); 

//echo $postfields; 

$curl_result = curl_exec ($curl_handle) or die ("There has been a CURL_EXEC error"); 
+1

你嘗試過什麼嗎? –

+0

@TAsk基本上它發送一個xml字符串來鏈接並得到這個響應 – user3481679

回答

6

Http(s)UrlConnection可能是您的首選武器:

public String sendData() throws IOException { 
    // curl_init and url 
    URL url = new URL("http://some.host.com/somewhere/to/"); 
    HttpURLConnection con = (HttpURLConnection) url.openConnection(); 

    // CURLOPT_POST 
    con.setRequestMethod("POST"); 

    // CURLOPT_FOLLOWLOCATION 
    con.setInstanceFollowRedirects(true); 

    String postData = "my_data_for_posting"; 
    con.setRequestProperty("Content-length", String.valueOf(postData.length())); 

    con.setDoOutput(true); 
    con.setDoInput(true); 

    DataOutputStream output = new DataOutputStream(con.getOutputStream()); 
    output.writeBytes(postData); 
    output.close(); 

    // "Post data send ... waiting for reply"); 
    int code = con.getResponseCode(); // 200 = HTTP_OK 
    System.out.println("Response (Code):" + code); 
    System.out.println("Response (Message):" + con.getResponseMessage()); 

    // read the response 
    DataInputStream input = new DataInputStream(con.getInputStream()); 
    int c; 
    StringBuilder resultBuf = new StringBuilder(); 
    while ((c = input.read()) != -1) { 
     resultBuf.append((char) c); 
    } 
    input.close(); 

    return resultBuf.toString(); 
} 

我不太肯定的HTTPS_VERIFYPEER-thing,但這可能會給你一個起點。

+0

我在創建DataOutputStream時得到異常.....任何幫助plz – user3481679

+0

鑄造一個字節到字符是一個壞主意。 – VGR