Created
June 11, 2011 21:52
-
-
Save sachin-handiekar/1020995 to your computer and use it in GitHub Desktop.
Using proxy with HttpClient
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
//~--- non-JDK imports -------------------------------------------------------- | |
import org.apache.http.Header; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.HttpHost; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.HttpStatus; | |
import org.apache.http.HttpVersion; | |
import org.apache.http.client.HttpClient; | |
import org.apache.http.client.methods.HttpGet; | |
import org.apache.http.client.params.HttpClientParams; | |
import org.apache.http.conn.ClientConnectionManager; | |
import org.apache.http.conn.params.ConnRoutePNames; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import org.apache.http.message.BasicHttpResponse; | |
import org.apache.http.params.BasicHttpParams; | |
import org.apache.http.params.HttpParams; | |
import org.apache.http.util.EntityUtils; | |
//~--- JDK imports ------------------------------------------------------------ | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.OutputStreamWriter; | |
import java.net.URI; | |
import java.net.URL; | |
import java.net.URLConnection; | |
import java.net.URLEncoder; | |
import java.util.Properties; | |
public class SampleHTTPCall { | |
public static void main(String[] args) throws Exception { | |
HttpHost proxy = new HttpHost("proxy.server.com", 80, "http"); | |
DefaultHttpClient httpclient = new DefaultHttpClient(); | |
try { | |
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, | |
proxy); | |
HttpHost target = new HttpHost("google.com", 80, "http"); | |
HttpGet req = new HttpGet("/"); | |
System.out.println("executing request to " + target + " via " | |
+ proxy); | |
HttpResponse rsp = httpclient.execute(target, req); | |
HttpEntity entity = rsp.getEntity(); | |
System.out.println("----------------------------------------"); | |
System.out.println(rsp.getStatusLine()); | |
Header[] headers = rsp.getAllHeaders(); | |
for (int i = 0; i < headers.length; i++) { | |
System.out.println(headers[i]); | |
} | |
System.out.println("----------------------------------------"); | |
if (entity != null) { | |
System.out.println(EntityUtils.toString(entity)); | |
} | |
} finally { | |
// When HttpClient instance is no longer needed, | |
// shut down the connection manager to ensure | |
// immediate deallocation of all system resources | |
httpclient.getConnectionManager().shutdown(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment