HttpClient如何使用代理服务器采用Get请求访问页面呢?
下文笔者讲述HttpClient使用代理服务器访问Get请求的方法及示例分享
1.定义代理信息 //代理设置 HttpHost proxy = new HttpHost("8.8.8.8", 8080); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 2.运行 httpclient.execute 获取HttpClient信息例:HttpClient使用代理服务器访问Get请求的示例
import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.impl.client.DefaultHttpClient; /** * HttpClient使用GET方式采用代理服务器访问页面 */ public class HttpClientGet { public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // 访问的目标站点,端口和协议 HttpHost targetHost = new HttpHost("www.java265.com"); // 代理的设置 HttpHost proxy = new HttpHost("8.8.8.8", 8080); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); // 目标地址 HttpGet httpget = new HttpGet("/"); System.out.println("目标: " + targetHost); System.out.println("请求: " + httpget.getRequestLine()); // 执行 HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } // 显示结果 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } if (entity != null) { entity.consumeContent(); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。