在银行工作的人都知道,银行的网络限制比较多,所以经常会使用到代理服务,简单的url直接处理过以后就可以。但是最近遇到了一个需求,就是通过代理服务访问一个网页,然后需要将网页的内容给还原了,然后再展现出来。之前没有处理过这样的东西,在网上各种找demo,找到了一个经测试可行的版本。
代码如下:
package proxy.test;
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;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
public class HttpClientProxy {
/**
* @param args
*/
public static void main(String[] args) {
String content = httpGet();
System.out.println("返回内容:"+content);
}
/**
* java使用代理发送http请求
* @return
*/
public static String httpGet() {
String ip = "139.159.254.106";
String content = null;
DefaultHttpClient httpclient = null;
try {
httpclient = new DefaultHttpClient();
/** 设置代理IP **/
HttpHost proxy = new HttpHost(ip, 3128);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
HttpGet httpget = new HttpGet("http://www.yiwugou.com/hu/01AA237B.html");
httpget.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,1000*30); //设置请求超时时间
httpget.setHeader("Proxy-Authorization","Basic eXVsb3JlOll1bG9yZVByb3h5MjAxMzo=");
httpget.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
httpget.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
HttpResponse responses = httpclient.execute(httpget);
HttpEntity entity = responses.getEntity();
content = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown(); //关闭连接
}
return content;
}
}
,
如果想要这个类的main函数跑起来,还需要一些jar,可以从这里下载:https://download.csdn.net/download/lyltiger/10042961?locationNum=4&fps=1。
本博客原文参考自:https://blog.csdn.net/top_code/article/details/8639491