使用commons HttpClient在Java中卷曲等效

时间:2013-07-11 18:30:50

标签: java apache curl apache-commons-httpclient

我使用Commons 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等价物:

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

帮助!

1 个答案:

答案 0 :(得分:2)

我认为你的内容是错误的。

替换:

 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));