Search code examples
javajsonposthttpclientput

POST/PUT in HttpClient


I'm trying to do a PUT/POST in my client application to update my DataBase. I'm using HttpClient.

Wich the following methods is the more correct, and why none of them works?

First: HTTP/1.1 415 Unsupported Media Type

   List <NameValuePair> nvps = new ArrayList <NameValuePair>();

   nvps.add(new BasicNameValuePair("Accept", "application/json"));
   nvps.add(new BasicNameValuePair("Content-Type", "application/json"));

   nvps.add(new BasicNameValuePair("userID", "user5"));
   nvps.add(new BasicNameValuePair("FirstName", "teste"));
   nvps.add(new BasicNameValuePair("LastName", "2"));

   httpPost.setEntity(new UrlEncodedFormEntity(nvps));

Second: HTTP/1.1 500 Internal Server Error

    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");

    JSONObject obj = new JSONObject();  
    obj.put("userID", "user5");
    obj.put("FirstName", "teste");
    obj.put("LastName", "2");

    httpPost.setEntity(new StringEntity(obj.toString(), "UTF-8"));

In the end I do: HttpResponse response = httpclient.execute(httpPost);

Or maybe the problem is the URL... I have: HttpPost httpPost= new HttpPost("http://localhost:8080/LULServices/webresources/entities.user"); I want to add a new User, in my user service (User table from de DataBase)

Thanks.


Solution

  • I've solved the problem of the second method just by changing the first capital letter to lower case. Really stupid error.. It is defined as 'firstName', and I wrote it as it was written in the DataBase table.