Friday, August 6, 2010

Send request to server and read the response from the server in android

AIM: Send request to server and read the response from the server  in android

Suppose,If you requested the some webUrl and you need to read the response it is giving to your request.By using this Code snippet you can send request to server and you can read the response also.

Code : 
-----------------------
// Declare the URL


 String sUrl="http://maps.google.com/maps/geo?q=40.714269,-74.005973&output=csv&sensor=false&key=ABQIAAAAyv6vVcm964cAVMz-QOdOABQLVNFQfUjPHIaxDwwO1rHli41i7BQY4IXR9MNshVtsCtC5BpoyYBOf0g";
                URL url;
                String response="";
                HttpURLConnection conn = null;
                try {
                        url = new URL(sUrl);
                        try {
                                conn = (HttpURLConnection) url.openConnection();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        BufferedReader rd = new BufferedReader(new InputStreamReader(conn .getInputStream()));
                        String line;
                        try {
                                while ((line = rd.readLine()) != null) {
                                        response=line;
                                }
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        rd.close();
                } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
              Toast.makeText( this, "Response:"+response, Toast.LENGTH_SHORT).show();
               Log.i("Response",""+response);

----------------------

BY this way we can send request and read the response as well.




5 comments:

  1. Fantastic! Now how do you have the info (response) displayed as a TextView instead of a toast???

    ReplyDelete
  2. However, in all of the discussion on this topic, one subject is usually overlooked.
    If you pass that exam, then you will have a demanding, yet rewarding
    job. Whether your goal is weight loss, fitness, overall good health, or proper nutrition, the
    modern physical therapist is qualified to conduct an overall health evaluation so they can customize a program that is appropriate for your current health
    status.
    Here is my homepage drugs to treat depression

    ReplyDelete

Android Developers Blog

Ram's shared items

Amazon Product Ads