Skip to content

Instantly share code, notes, and snippets.

@cjohansen
Created January 13, 2011 09:11
Show Gist options
  • Select an option

  • Save cjohansen/777615 to your computer and use it in GitHub Desktop.

Select an option

Save cjohansen/777615 to your computer and use it in GitHub Desktop.
package com.simplehttp;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
public class OpenURI {
public final static String USER_AGENT = "My simple user URI opener user agent";
public static String openURI(URI uri, HttpContext httpContext) {
HttpGet httpGet = new HttpGet(uri);
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
httpGet.addHeader("User-Agent", USER_AGENT);
HttpResponse response = httpClient.execute(httpGet, httpContext);
return EntityUtils.toString(response.getEntity());
} catch (Exception e) {
return null;
}
}
public static String openURI(String uriString, HttpContext httpContext) {
try {
return openURI(new URI(uriString), httpContext);
} catch (URISyntaxException e) {
return null;
}
}
public static String openURI(URI uri) {
return openURI(uri, new BasicHttpContext());
}
public static String openURI(String uri) {
return openURI(uri, new BasicHttpContext());
}
}
// Usage:
import static com.simplehttp.OpenURI.openURI;
// ...
String body = openURI(url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment