搭建proxy伺服器

近期使用爬虫爬取数据,需要使用代理,记录一下搭建proxy伺服器的过程,这里使用的是squid.

搭建proxy伺服器

这里使用的是squid.

安装

1
yum install -y squid

配置

因为是在内网环境中,所以只对squid进行了简单的配置。各配置项含义和其他配置可以参考鳥哥的 Linux 私房菜: Proxy 伺服器

配置文件为/etc/squid/squid.conf, 简单修改以下几个方面:

  1. 增加一行http_access allow allhttp_accesshttp_deny是有顺序的, 匹配到第一个后就不再继续匹配, 所以特别需要注意顺序.
  2. 修改http_port8999,不要使用默认的3128,会被很多网站屏蔽。

启动

  1. 启动前执行squid -z,根据配置文件重建缓存。
  2. /etc/init.d/squid start启动。
  3. 如果想开启启动squid,执行chkconfig squid on

java中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientTest {
public static void main(String args[]) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpHost target = new HttpHost("www.baidu.com");
HttpHost proxy = new HttpHost("myproxy.server", 8999, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet request = new HttpGet("/");
request.setConfig(config);
System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);
CloseableHttpResponse response = httpclient.execute(target, request);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}

参考

  1. 鳥哥的 Linux 私房菜: Proxy 伺服器