Rajeev N B
Rajeev N B

Reputation: 1363

500 Internal Server Error with POST Requests

Here is my code for the POST request to the server.

The JSON to be posted to the server :

{  
"User": {    
"Name": "dog","Password": "123"  }

}

How I am creating the JSON Object

    object = new JSONObject();
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("Name", "dog");
        jsonObject.put("Password", "123");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        object.put("User", jsonObject);
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

Posting to the server as

    public HttpResponse request(JSONObject request)
        throws ClientProtocolException, IOException, IllegalStateException,
            JSONException {
            client = (DefaultHttpClient) WebClientDevWrapper
                    .getNewHttpClient();

    HttpPost post = new HttpPost(
            "https://wbapi.cloudapp.net:443/api/User/LocalLogin/");
    post.setEntity(new StringEntity(request.toString(), "utf-8"));
    HttpResponse response = client.execute(post);
    return response;
}

Along with classes provided by Paresh Mayani Here Send HTTPS Post Request to the server

I am getting the response object. But my response.getStatusLine() keeps showing 500/ Internal server error for only POST requests.

Note : GET requests are working fine.

What is the Problem in my code ? How can I tackle this error ?

Changed the request code as ( As recommended by Bhavdip Pathar)

public HttpResponse request(JSONObject request)
        throws ClientProtocolException, IOException, IllegalStateException,
        JSONException {

    HttpPost post = new HttpPost(
            "https://wbapi.cloudapp.net:443/api/User/LocalLogin/");
    // post.setEntity(new StringEntity(request.toString(), "utf-8"));
    StringEntity entity = new StringEntity(request.toString(), HTTP.UTF_8);
    entity.setContentType("application/json");
    post.setHeader("Content-Type", "application/json");
    post.setHeader("Accept", "application/json");
    post.setEntity(entity);
    HttpResponse response = client.execute(post);
    return response;
}

I did set application/json and voila , I am getting HTTP/200 OK.

Upvotes: 4

Views: 27618

Answers (1)

Bhavdip Sagar
Bhavdip Sagar

Reputation: 1971

Set contentType: "application/json"

Upvotes: 6

Related Questions