Skip to content Skip to sidebar Skip to footer

Send Information From Android Application To A Web Service And Back

Let's say I need to create an android app which will, on the click of a button, send a number from a textbox to a web service. This service will send back a string saying 'your num

Solution 1:

I think the best way to achieve your work is using HTTP post, to do that you need 5 things:

1) do a Json object: JSONObject jsonobj = new JSONObject(); //you need to fill this object

2) Create a http client:

DefaultHttpClienthttpclient=newDefaultHttpClient();

3) create a http response and a http request:

HttpResponse httpresponse;
HttpPost httppostreq;

3) complete your http request:

httppostreq = new HttpPost(SERVER_URL);

4) attach the json object (the one you will send):

StringEntityse=newStringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
httppostreq.setEntity(se);

5) to get the response: httpresponse = httpclient.execute(httppostreq); //as a Json object

2 observations: you need to catch the possibles exceptions and always a http request must be done in a different thread.

Solution 2:

Depends pretty much on how the webservice is build up. Because your question has a lack of detail here I can only give you the advice to stick with the Android HTTP client if you want to have your requests managed.

If you only want to send/receive plain data from a webservice you can use Sockets and write/read to their output/inputstreams. Of course you have to implement the HTTP protocol on your own this way. Nevertheless for simple requests this is my preferred method. If you are not known to the HTTP protocol I suggest to take a look at browserplugins like Live HTTP Headers.

Example querying the google startpage:

try {
        Socketsocket=newSocket("google.com", 80);
        PrintWriterwriter=newPrintWriter(socket.getOutputStream());
        writer.print("GET /\r\nHost:google.com\r\n\r\n");
        writer.flush();

        InputStreamReaderisr=newInputStreamReader(socket.getInputStream());
        BufferedReaderreader=newBufferedReader(isr);
        for(String s; (s = reader.readLine()) != null;) {
            System.out.printf("%s", s);
        }
        isr.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

Post a Comment for "Send Information From Android Application To A Web Service And Back"