httpclient:Ip 代理
参考:http://blog.csdn.net/sdfiiiiii/article/details/70432060 http://blog.csdn.net/qy20115549/article/details/54945974
第一篇博客可以获取http://www.xicidaili.com/网站上所有的代理ip,并测试可不可以用(貌似不是很准),可用的代理ip放到一个list中
第二篇博客是直接将代理ip设置进代码内,可以用作测试ip可不可用
第一篇博客
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
* 获取代理IP,需要
* com.alibaba.fastjson.JSONObject以及Jsoup
*/
public class ProxyCralwerUnusedVPN { ThreadLocal<Integer> localWantedNumber = new ThreadLocal<Integer>();
ThreadLocal<List<ProxyInfo>> localProxyInfos = new ThreadLocal<List<ProxyInfo>>(); public static void main(String[] args) {
ProxyCralwerUnusedVPN proxyCrawler = new ProxyCralwerUnusedVPN();
/**
* 想要获取的代理IP个数,由需求方自行指定。(如果个数太多,将导致返回变慢)
*/
proxyCrawler.startCrawler(1);
} /**
* 暴露给外部模块调用的入口
* @param wantedNumber 调用方期望获取到的代理IP个数
*/
public String startCrawler(int wantedNumber) {
localWantedNumber.set(wantedNumber); kuaidailiCom("http://www.xicidaili.com/nn/", 15);
kuaidailiCom("http://www.xicidaili.com/nt/", 15);
kuaidailiCom("http://www.xicidaili.com/wt/", 15);
kuaidailiCom("http://www.kuaidaili.com/free/inha/", 15);
kuaidailiCom("http://www.kuaidaili.com/free/intr/", 15);
kuaidailiCom("http://www.kuaidaili.com/free/outtr/", 15); /**
* 构造返回数据
*/
ProxyResponse response = new ProxyResponse();
response.setSuccess("true");
Map<String, Object> dataInfoMap = new HashMap<String, Object>();
dataInfoMap.put("numFound", localProxyInfos.get().size());
dataInfoMap.put("pageNum", 1);
dataInfoMap.put("proxy", localProxyInfos.get());
response.setData(dataInfoMap);
String responseString = JSONObject.toJSON(response).toString();
System.out.println(responseString);
return responseString;
} private void kuaidailiCom(String baseUrl, int totalPage) {
String ipReg = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3} \\d{1,6}";
Pattern ipPtn = Pattern.compile(ipReg); for (int i = 1; i < totalPage; i++) {
if (getCurrentProxyNumber() >= localWantedNumber.get()) {
return;
}
try {
Document doc = Jsoup.connect(baseUrl + i + "/")
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
.header("Accept-Encoding", "gzip, deflate, sdch")
.header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6")
.header("Cache-Control", "max-age=0")
.header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36")
.header("Cookie", "Hm_lvt_7ed65b1cc4b810e9fd37959c9bb51b31=1462812244; _gat=1; _ga=GA1.2.1061361785.1462812244")
.header("Host", "www.kuaidaili.com")
.header("Referer", "http://www.kuaidaili.com/free/outha/")
.timeout(30 * 1000)
.get();
Matcher m = ipPtn.matcher(doc.text()); while (m.find()) {
if (getCurrentProxyNumber() >= localWantedNumber.get()) {
break;
}
String[] strs = m.group().split(" ");
if (checkProxy(strs[0], Integer.parseInt(strs[1]))) {
System.out.println("获取到可用代理IP\t" + strs[0] + "\t" + strs[1]);
addProxy(strs[0], strs[1], "http");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} private static boolean checkProxy(String ip, Integer port) {
try {
//http://1212.ip138.com/ic.asp 可以换成任何比较快的网页
Jsoup.connect("http://1212.ip138.com/ic.asp")
.timeout(2 * 1000)
.proxy(ip, port)
.get();
return true;
} catch (Exception e) {
return false;
}
} private int getCurrentProxyNumber() {
List<ProxyInfo> proxyInfos = localProxyInfos.get();
if (proxyInfos == null) {
proxyInfos = new ArrayList<ProxyInfo>();
localProxyInfos.set(proxyInfos);
return 0;
}
else {
return proxyInfos.size();
}
}
private void addProxy(String ip, String port, String protocol){
List<ProxyInfo> proxyInfos = localProxyInfos.get();
if (proxyInfos == null) {
proxyInfos = new ArrayList<ProxyInfo>();
proxyInfos.add(new ProxyInfo(ip, port, protocol));
}
else {
proxyInfos.add(new ProxyInfo(ip, port, protocol));
}
}
} class ProxyInfo {
private String userName = "";
private String ip;
private String password = "";
private String type;
private String port;
private int is_internet = 1;
public ProxyInfo(String ip, String port, String type) {
this.ip = ip;
this.type = type;
this.port = port;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public int getIs_internet() {
return is_internet;
}
public void setIs_internet(int is_internet) {
this.is_internet = is_internet;
}
} class ProxyResponse {
private String success;
private Map<String, Object> data;
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
}

第二篇博客
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection; public class GetHtml {
public static void main(String[] args) throws UnsupportedEncodingException {
//输入代理ip,端口,及所要爬取的url
gethtml("121.61.101.222",808,"http://club.autohome.com.cn/bbs/forum-c-2533-1.html?orderby=dateline&qaType=-1"); }
public static String gethtml(String ip,int port,String url) throws UnsupportedEncodingException{
URL url1 = null;
try {
url1 = new URL(url);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
InetSocketAddress addr = null;
//代理服务器的ip及端口
addr = new InetSocketAddress(ip, port);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http proxy
InputStream in = null;
try {
URLConnection conn = url1.openConnection(proxy);
conn.setConnectTimeout(3000);
in = conn.getInputStream();
} catch (Exception e) {
System.out.println("ip " + " is not aviable");//异常IP
} String s = convertStreamToString(in);
System.out.println(s);
return s; }
public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
if (is == null)
return "";
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"gb2312"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "/n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString(); }
}
httpclient:Ip 代理的更多相关文章
- C#5.0异步编程 HttpClient IP代理验证原码
//访问HttpClient 代码 public async Task<string> VerifyProxy(string url, string proxy = "" ...
- HttpClient(二)HttpClient使用Ip代理与处理连接超时
前言 其实前面写的那一点点东西都是轻轻点水,其实HttpClient还有很多强大的功能: (1)实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等) (2)支持自动转向 (3)支持 ...
- (四)HttpClient 使用代理 IP
第一节: HttpClient 使用代理 IP 在爬取网页的时候,有的目标站点有反爬虫机制,对于频繁访问站点以及规则性访问站点的行为,会采集屏蔽IP措施. 这时候,代理IP就派上用场了. 关于代理IP ...
- 通过httpClient设置代理Ip
背景: 我们有个车管系统,需要定期的去查询车辆的违章,之前一直是调第三方接口去查,后面发现数据不准确(和深圳交警查的对不上),问题比较多.于是想干脆直接从深圳交警上查,那不就不会出问题了吗,但是问题又 ...
- 免费IP代理池定时维护,封装通用爬虫工具类每次随机更新IP代理池跟UserAgent池,并制作简易流量爬虫
前言 我们之前的爬虫都是模拟成浏览器后直接爬取,并没有动态设置IP代理以及UserAgent标识,本文记录免费IP代理池定时维护,封装通用爬虫工具类每次随机更新IP代理池跟UserAgent池,并制作 ...
- python获取ip代理列表爬虫
最近练习写爬虫,本来爬几张mm图做测试,可是爬到几十张的时候就会返回403错误,这是被网站服务器发现了,把我给屏蔽了. 因此需要使用代理IP.为了方便以后使用,我打算先写一个自动爬取ip代理的爬虫,正 ...
- 开源IP代理池续——整体重构
开源IP代理池 继上一篇开源项目IPProxys的使用之后,大家在github,我的公众号和博客上提出了很多建议.经过两周时间的努力,基本完成了开源IP代理池IPProxyPool的重构任务,业余时间 ...
- 被IP代理网站屏蔽了,真是跪了
被IP代理网站http://www.xicidaili.com/nn/屏蔽了,真是跪了 T T
- Linux IP代理筛选系统(shell+proxy)
代理的用途 其实,除了抓取国外网页需要用到IP代理外,还有很多场景会用到代理: 通过代理访问一些国外网站,绕过被某国防火墙过滤掉的网站 使用教育网的代理服务器,可以访问到大学或科研院所的内部网站资源 ...
随机推荐
- C#自定义类型数组排序
在数组或者集合中对自定义类型进行排序分为两种方法. 1.如果这个自定义类型是自己定义编写的,那么我可以使它继承ICompareable<T>接口,实现其中的CompareTo(Object ...
- selector的button选中处理问题
1.背景介绍 在做Android项目开发的时候,有时我们须要对button做一些特殊的处理,比方button点击的时候会有一个动画的效果,实际上就是几张图片在短时间的切换.再比方有时候我们须要对界面的 ...
- inception安装步骤---自己整理的安装步骤
inception安装步骤---自己整理的安装步骤2015-09-18 15:51 6185人阅读 评论(1) 收藏 举报 分类: inception相关版权声明:本文为博主原创文章,未经博主允许不得 ...
- eclipse的快捷键(常用)
1. Ctrl+O 显示类中方法和属性的大纲,能快速定位类的方法和属性,在查找Bug时非常有用. 2. Ctrl+M 窗口最大化和还原,用户在窗口中进行操作时,总会觉得当前窗口小(尤其在编写代码时), ...
- 【BZOJ1110】[POI2007]砝码Odw 贪心
[BZOJ1110][POI2007]砝码Odw Description 在byteotian公司搬家的时候,他们发现他们的大量的精密砝码的搬运是一件恼人的工作.公司有一些固定容量的容器可以装这些砝码 ...
- C++ Lambda表达式和仿函数笔记
C++11中引入了Lambda表达式,其语法如下: [capture list](parameter list)->return type { function body } 参考博文:C++ ...
- BZOJ 2069 POI2004 ZAW 堆优化Dijkstra
题目大意:给定一张无向图.每条边从两个方向走各有一个权值,求从点1往出走至少一步之后回到点1且不经过一条边多次的最短路 显然我们须要从点1出发走到某个和点1相邻的点上,然后沿最短路走到还有一个和点1相 ...
- SpringBoot-(5)-properties的使用
项目中经常需要进行一些配置,一般会使用springboot默认的application.properties文件,也可以自己创建配置文件 一,application.properties配置 logg ...
- CodeForces - 385E Bear in the Field —— 矩阵快速幂
题目链接:https://vjudge.net/problem/CodeForces-385E E. Bear in the Field time limit per test 1 second me ...
- 基于BASYS2的VHDL程序——数字钟(改进版)
扩展到时分秒.加了入调时电路,但不知道为什么有两个按键不好使.而且不知道以何种方式假如按键消抖电路,因为加入后会多个时钟控制一个信号,物理不可实现.调试电路待解决.还有,四个数目管中间的那两个圆点怎么 ...