Android Programming: DefaultHttpClient GET Request

This article will briefly describe the method to form and receive an HTTP GET request in Android. The first code snippet listed below shows how to form the request and receive the data back from the server.  The second shows a function that can be used to read the InputStream and save it to a string. The entire process isn’t very difficult, but can be a bit confusing the first time you try to piece it together. The code below still requires some additional code to fail more elegantly in case of a broken internet connection, website error, etc., but should copy/paste pretty easily into applications.

   1: public String getUrlData(String url) {
   2:     String websiteData = null;
   3:     try {
   4:         DefaultHttpClient client = new DefaultHttpClient();
   5:         URI uri = new URI(url);
   6:         HttpGet method = new HttpGet(uri);
   7:         HttpResponse res = client.execute(method);
   8:         InputStream data = res.getEntity().getContent();
   9:         websiteData = generateString(data);
  10:     } catch (ClientProtocolException e) {
  11:         // TODO Auto-generated catch block
  12:         e.printStackTrace();
  13:     } catch (IOException e) {
  14:         // TODO Auto-generated catch block
  15:         e.printStackTrace();
  16:     } catch (URISyntaxException e) {
  17:         // TODO Auto-generated catch block
  18:         e.printStackTrace();
  19:     }
  20:
  21:     return websiteData;
  22: }
   1: public String generateString(InputStream stream) {
   2:     InputStreamReader reader = new InputStreamReader(stream);
   3:     BufferedReader buffer = new BufferedReader(reader);
   4:     StringBuilder sb = new StringBuilder();
   5:
   6:     try {
   7:         String cur;
   8:         while ((cur = buffer.readLine()) != null) {
   9:             sb.append(cur + "\n");
  10:         }
  11:     } catch (IOException e) {
  12:         // TODO Auto-generated catch block
  13:         e.printStackTrace();
  14:     }
  15:
  16:     try {
  17:         stream.close();
  18:     } catch (IOException e) {
  19:         // TODO Auto-generated catch block
  20:         e.printStackTrace();
  21:     }
  22:     return sb.toString();
  23: }

Tags: , ,

Leave a Reply