0

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"}'
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301
  • 2
    Have you verified this needs to be as a request parameter and not the body of the POST? Perhaps the contents are too large for use as a parameter, it is difficult to say without knowing what the Application's JSON form is. It's also difficult without knowing anything about the "server" other than you are posting to a URI that ends in `apps.json`. – Paul Bilnoski Aug 14 '15 at 20:36
  • yes, request Parameter – Nuñito Calzada Aug 14 '15 at 20:43
  • It works with your `curl` command but not your java code? – Paul Bilnoski Aug 14 '15 at 20:56
  • indeed, it works using the curl command – Nuñito Calzada Aug 14 '15 at 21:04
  • 2
    The curl command doesn't make much sense. -d is supposed to take something like "foo=bar" as argument, because the data is supposed to be sent in the application/x-www-form-urlencoded format. But it's sending raw JSON, without any parameter name. In your Java code, on the contrary, you'res sending a parameter named "app". My guess is that the server indeed expects the JSON as the body of the request. – JB Nizet Aug 15 '15 at 06:32

1 Answers1

1

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);
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301