json序列化为Java HttpPost中的请求参数

时间:2015-08-14 20:33:34

标签: java json rest http restful-url

我必须发送一个带有json序列化对象的请求作为参数,但是我得到了一个内部服务器错误(500)。这是我的代码:

 GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = = gsonBuilder.create();
    HttpParams myHttpParams=new BasicHttpParams();
    Application myApp = new Application();
    myHttpParams.setParameter("app", gson.toJson(myApp));
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost request = new HttpPost("https://foo.com/developers/apps.json");
    request.setParams(myHttpParams);
        request.addHeader("Authorization", "Basic cmljYXJkLm8sbGVAZ31haWwuY79tOkljb15vZmNvbWwzMDA=");
        request.addHeader("Accept", "application/json");
    HttpResponse response = client.execute(request);

    System.out.println("\nResponse Code SaveOrUpdate : " 
                    + response.getStatusLine().getStatusCode());
            System.out.println("\nResponse Code SaveOrUpdate : " 
                    + response.getStatusLine().getReasonPhrase());

样本创建请求命令:

curl -X POST -H "Authorization: Basic cmljYXJkLm8sbGVAZ31haWwuY79tOkljb15vZmNvbWwzMDA=" "http://foo.com/developers/apps.json" -d '{"name": "myApp", "description" : "My app description lines go here", "callbackurl" : "http://my.callback.url"}'

1 个答案:

答案 0 :(得分:1)

事实上,正如你所说,它可以使用

HttpClient client = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost("https://foo.com/developers/apps.json");

        StringEntity input = new StringEntity(gson.toJson(myApp));
        input.setContentType("application/json;charset=UTF-8");
        input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
        request.setEntity(input);