Last active
December 20, 2015 05:09
-
-
Save VenomVendor/6075840 to your computer and use it in GitHub Desktop.
One Line Http Get Request with Response in Android.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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(url1); | |
HttpResponse response = httpClient.execute(httpGet); | |
HttpEntity httpEntity = response.getEntity(); | |
String res = EntityUtils.toString(httpEntity); | |
System.out.println(res); | |
/* Best Practice, *****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 | |
{ | |
System.out.println("Failure"); | |
} | |
/* 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; | |
} | |
// <uses-permission android:name="android.permission.INTERNET" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment