org.apache.http.client.HttpResponseException:错误请求 - 通过REST发送JSON请求

时间:2016-06-24 13:43:21

标签: java json apache post

我收到错误org.apache.http.client.HttpResponseException:我尝试运行此程序时出现错误请求。

你能帮我理解我应该在哪里修改代码吗?

我正在使用以下库 HttpClient的-4.4.1.jar 的HttpCore-4.4.1.jar 共享记录-1.1.2.jar

org.apache.http.client.HttpResponseException:错误请求

以下是代码:

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class Test {
public static void main(String args[]) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost("http://localhost:8080/engine-rest/process-definition/key/demo-scaling/start");
    try {
        StringEntity input = new StringEntity("(\"variables\":{}, \"businessKey\" : \"AAA001\")");
        postRequest.addHeader("Accept", "application/json");
        postRequest.setEntity(input);
        postRequest.addHeader("Content-Type", "application/json");
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(postRequest, responseHandler);
        System.out.println(responseBody);
    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

}

1 个答案:

答案 0 :(得分:1)

好的,试试这个:

 HttpClient httpClient = HttpClientBuilder.create().build();

    try {
        HttpPost request = new HttpPost("http://localhost:8080/engine-rest/process-definition/key/demo-scaling/start");
        StringEntity params =new StringEntity("variables={\"businessKey\":\"AAA001\"}");
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);

        System.out.println(response);
    }catch (Exception ex) {
        // handle Exceptions
    }

使用httpclientbuilder获取客户端(DefaultHttpClient - &gt; Deprecated),我不确定您是否拥有有效的JSON数据,这只是我的建议。