Send httpget request in Android, receive, read response & print result in single line.

Any connection to server has to called inside Async Task.


 <uses-permission android:name="android.permission.INTERNET" /> 


 /* Single line request with response */ 

  System.out.println(EntityUtils.toString(new DefaultHttpClient().execute(new HttpGet("http://www.VenomVendor.com")).getEntity()));


/* Equivalent for the above */

  String url = "http://www.VenomVendor.com";
  HttpClient httpClient = new DefaultHttpClient();
  HttpGet httpGet = new HttpGet(url);
  HttpResponse response = httpClient.execute(httpGet);
  HttpEntity httpEntity = response.getEntity();
  String res = EntityUtils.toString(httpEntity);
  System.out.println(res);


 /* Best Practice, *****Also Surround with try-catch***** */

  String url = "http://www.VenomVendor.com";
  HttpClient httpClient = new DefaultHttpClient();
  HttpGet httpGet = new HttpGet(url);
  HttpResponse response = httpClient.execute(httpGet);
    if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK && response.getEntity()!=null)
      {
        HttpEntity httpEntity = response.getEntity();
        String res = EntityUtils.toString(httpEntity);
        System.out.println(res);
      }
    else
      {
      Log.wtf("Error in Server","Operation Success, Patient Dead");
      }


 /* OLD J2ME Method *** DIFFRERENCE IS IN CONVERTING THE RESPONSE TO `STRING` *** */
 
 String url = "http://www.VenomVendor.com";
 HttpClient httpClient = new DefaultHttpClient();
 HttpGet httpGet = new HttpGet(url);
 HttpResponse response = httpClient.execute(httpGet);
 HttpEntity httpEntity = response.getEntity();
 InputStream iStream = httpEntity.getContent();
 
 StringBuilder sBuilder = inputStreamToString(iStream);
 
 if (sBuilder != null) 
 {
  System.out.println(sBuilder.toString());
 } 
 else 
 {
  System.out.println("WTF");
 }

  /** METHOD TO CONVERT INPUTSTREAM TO STRING **/
 private StringBuilder inputStreamToString(InputStream iStream) {
  String line = "";
  StringBuilder finalRespose = new StringBuilder();
  BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));

  try {
    while ((line = reader.readLine()) != null) 
     {
      finalRespose.append(line);
     }
    } catch (IOException e) {
      e.printStackTrace();
    }
  return finalRespose;
 }



Fork @ GitHub Gist