Guille
Guille

Reputation: 2320

to call REST (POST) webservice from Android

I'mm trying to create a webservice and use it from Android. It's working the GET method but I don't get to call the POST method.

@Path("/dictionary")
public class DictionaryWebService {

private final static String ID = "id";
private final static String WORD = "palabra";
private final static String DESCRIPTION = "description";

.....  
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Word postNewWord(MultivaluedMap<String, String> newWord) {

    Word dict;


    String id = newWord.getFirst(ID);
    String word = newWord.getFirst(WORD);
    String description = newWord.getFirst(DESCRIPTION);

    dict = new Word(id, word, description);
    dictionary.putNewWord(dict);

    System.out.println("New Word info: " + dict.toString());

    return dict;

    }
}

My android code is:

        @Override
        public void onClick(View arg0) {
            System.out.println("onClick!!!");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://10.0.2.2:8080/DictionaryWebService/rest/dictionary/");
            post.setHeader("content-type", "application/json");

            //Construimos el objeto cliente en formato JSON
            JSONObject dato = new JSONObject();



            try {


                dato.put("id", txtId.getText().toString()); 
                dato.put("palabra", txtWord.getText().toString());
                dato.put("description", txtDescription.getText().toString());

                StringEntity entity = new StringEntity(dato.toString());
                post.setEntity(entity);

                HttpResponse resp = httpClient.execute(post);
                String respStr = EntityUtils.toString(resp.getEntity());


                System.out.println("OKAY!");

            .....

        }
    });

I don't know but I can't execute the webservice,,, it's not called. What is wrong?? Could someone help me? The onclick method finishes without any error.

Thank you.

Upvotes: 3

Views: 12067

Answers (2)

Paul Manning
Paul Manning

Reputation: 21

I used your code and it works fine? the only change I made was the I set the post header to;

post.setHeader("content-type", "application/json; charset=UTF-8");

Upvotes: 2

Tony D
Tony D

Reputation: 1531

I do this a bit differently than you, but an example in SO I have seen that is similar to yours from the client perspective ( Http post with parameters not working ) uses an additional post.setHeader call:

post.setHeader("Accept", "application/json");

This is in addition to the post.setHeader call you already make.

The example from the link is also a nice short test for checking everything else is working (sanity check).

Hope this helps.

Upvotes: 1

Related Questions