简体   繁体   中英

json serialized as a request parameter in Java HttpPost

I have to send a request with a json serialized object as a parameter, But i got a Internal Server Error (500). Here my code:

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

Sample creation request command:

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"}'

Indeed, as you said, it works using

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM