2013-07-11 30 views
1

我正在使用Commons HttpClient以一些字符串內容作爲參數發送post請求。以下是我的代碼:在Java中使用commons的curl等效HttpClient

// obtain the default httpclient 
    client = new DefaultHttpClient(); 

    // obtain a http post request object 
    postRequest = new HttpPost(stanbolInstance); 
    postRequest.setHeader("Accept", "application/json"); 

    // create an http param containing summary of article 
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
    nameValuePairs.add(new BasicNameValuePair("data", content)); 

    try { 
     // add the param to postRequest 
     postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    try { 
     // obtain the response 
     response = client.execute(postRequest); 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

這裏,stanbolInstance是:http://dev.iks-project.eu:8081/enhancer 它不工作。以下是例外:

Problem accessing /enhancer. Reason: 
<pre> The parsed byte array MUST NOT be NULL!</pre></p><h3>Caused by:</h3><pre>java.lang.IllegalArgumentException: The parsed byte array MUST NOT be NULL! 

以下是捲曲相當於它的工作原理:

curl -X POST -H "Accept: text/turtle" -H "Content-type: text/plain" --data "The Stanbol enhancer can detect famous cities such as Paris and people such as Bob Marley." http://dev.iks-project.eu:8081/enhancer 

幫助!

+0

檢查的 '內容' – sadhu

+0

@sadhu內容:這是好的! – kunal18

回答

1

我認爲你的內容是錯誤的。

替換:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
    nameValuePairs.add(new BasicNameValuePair("data", content)); 

    try { 
     // add the param to postRequest 
     postRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

postRequest.setEntity(new StringEntity(content)); 
+0

感謝它的工作!其實我從vogella.com跟隨了一個教程 – kunal18

相關問題