Skip to content

Instantly share code, notes, and snippets.

@farandal
Created March 18, 2013 04:33
Show Gist options
  • Save farandal/5185110 to your computer and use it in GitHub Desktop.
Save farandal/5185110 to your computer and use it in GitHub Desktop.
Http Helper -> Java Class to read the content of a webpage
package controllers;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class HttpHelper {
public static String get(String url) {
String result;
result = "";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
result = result + output;
}
httpClient.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment