如果翻过墙,或者做过渗透啥的,肯定对代理不陌生,说白了,代理服务器就是一个中转站,你对目标网址的请求都会进过代理服务器去请求,类似于一个被你操控的傀儡,别人能知道的也只能是这个代理,从而提升安全性和访问一些受限制的网站。

实现方式

方法一 :使用系统属性来完成代理设置, 这种方法比较简单, 但是不能对单独的连接来设置代理:

方法二 :使用Proxy来对每个连接实现代理, 这种方法只能在jdk 1.5以上的版本使用(包含jdk1.5), 优点是可以单独的设置每个连接的代理, 缺点是设置比较麻烦:

先上结果

发送GET请求出现异常!	113.71.209.222	->	异常
{ip:'113.123.118.129',address:'山东省滨州市 电信'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'144.255.233.100',address:'山东省 电信'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'116.2.97.36',address:'辽宁省沈阳市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 182.91.66.251 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'42.6.232.245',address:'辽宁省 联通'}
发送GET请求出现异常! 27.212.106.212 -> 异常
{ip:'183.158.154.222',address:'浙江省杭州市 电信'}
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 106.113.122.194 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 121.225.84.216 -> 异常
发送GET请求出现异常! 111.155.116.232 -> 异常
发送GET请求出现异常! 106.44.81.188 -> 异常
发送GET请求出现异常! 60.187.173.190 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'118.80.223.249',address:'山西省阳泉市 联通'}
发送GET请求出现异常! 119.130.24.74 -> 异常
发送GET请求出现异常! 123.116.57.125 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'未知国家 '}
发送GET请求出现异常! 171.212.200.237 -> 异常
发送GET请求出现异常! 183.158.154.222 -> 异常
{ip:'139.208.195.31',address:'吉林省延边州 联通'}
{ip:'113.140.139.7',address:'陕西省西安市 电信'}
{ip:'123.131.89.41',address:'山东省潍坊市 联通'}
{ip:'121.41.82.138',address:'浙江省杭州市 阿里云BGP数据中心'}
发送GET请求出现异常! 116.54.78.99 -> 异常
{ip:'116.234.58.218',address:'上海市 电信'}
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 60.166.89.211 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'175.18.57.147',address:'吉林省辽源市 联通'}
发送GET请求出现异常! 101.28.93.196 -> 异常
{ip:'221.215.190.141',address:'山东省青岛市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'171.14.37.251',address:'河南省信阳市 电信'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'218.78.213.174',address:'上海市 电信'}
{ip:'114.235.80.161',address:'江苏省徐州市 电信'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'101.86.86.101',address:'上海市 电信'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'119.187.37.87',address:'山东省 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 123.122.150.242 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 175.165.101.48 -> 异常
发送GET请求出现异常! 122.72.32.74 -> 异常
发送GET请求出现异常! 114.237.155.155 -> 异常
{ip:'115.234.155.155',address:'浙江省温州市 电信'}
发送GET请求出现异常! 121.56.190.52 -> 异常
{ip:'122.236.153.216',address:'浙江省绍兴市 电信'}
发送GET请求出现异常! 180.173.109.149 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 119.182.47.86 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 114.217.243.25 -> 异常
发送GET请求出现异常! 117.78.51.231 -> 异常
{ip:'122.97.159.144',address:'江苏省 联通'}
{ip:'123.166.23.42',address:'黑龙江省哈尔滨市 电信'}
发送GET请求出现异常! 125.71.133.237 -> 异常
{ip:'114.102.46.16',address:'安徽省马鞍山市 电信'}
{ip:'1.59.74.243',address:'黑龙江省大庆市 联通'}
发送GET请求出现异常! 1.61.245.127 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'39.64.193.40',address:'山东省 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'黑龙江省七台河市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 175.172.216.95 -> 异常
{ip:'221.198.63.96',address:'天津市 联通'}
发送GET请求出现异常! 123.120.219.129 -> 异常
{ip:'111.172.227.239',address:'湖北省武汉市 电信'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
{ip:'221.198.63.96',address:'天津市 联通'}
耗时:232.66

国内免费代理的特点是又慢又卡,没办法,谁让人家免费呢,上面出现GET方式请求异常可能有两个可能

1、超时(我设置了3s超时)

2、代理不能用(这就没办法了)

具体实现

方法一 :使用系统属性来完成代理设置, 这种方法比较简单, 但是不能对单独的连接来设置代理:

public static void main(String[] args) {
Properties prop = System.getProperties();
// 设置http访问要使用的代理服务器的地址
prop.setProperty("http.proxyHost", "192.168.0.254");
// 设置http访问要使用的代理服务器的端口
prop.setProperty("http.proxyPort", "8080");
// 设置不需要通过代理服务器访问的主机,可以使用*通配符,多个地址用|分隔
prop.setProperty("http.nonProxyHosts", "localhost|192.168.0.*");
// 设置安全访问使用的代理服务器地址与端口
// 它没有https.nonProxyHosts属性,它按照http.nonProxyHosts 中设置的规则访问
prop.setProperty("https.proxyHost", "192.168.0.254");
prop.setProperty("https.proxyPort", "443");
// 使用ftp代理服务器的主机、端口以及不需要使用ftp代理服务器的主机
prop.setProperty("ftp.proxyHost", "192.168.0.254");
prop.setProperty("ftp.proxyPort", "2121");
prop.setProperty("ftp.nonProxyHosts", "localhost|192.168.0.*");
// socks代理服务器的地址与端口
prop.setProperty("socksProxyHost", "192.168.0.254");
prop.setProperty("socksProxyPort", "8000");
// 设置登陆到代理服务器的用户名和密码
Authenticator.setDefault(new MyAuthenticator("userName", "Password"));
}
static class MyAuthenticator extends Authenticator {
private String user = "";
private String password = "";
public MyAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
returnnew PasswordAuthentication(user, password.toCharArray());
}
}

别着急,别看到这个就头大,这是API接口说明

方法二 :使用Proxy来对每个连接实现代理, 这种方法只能在jdk 1.5以上的版本使用(包含jdk1.5), 优点是可以单独的设置每个连接的代理, 缺点是设置比较麻烦:

public static void main(String[] args) {
try {
URL url = new URL("http://www.baidu.com");
// 创建代理服务器
InetSocketAddress addr = new InetSocketAddress("192.168.0.254",8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http 代理
// 如果我们知道代理server的名字, 可以直接使用
URLConnection conn = url.openConnection(proxy);
InputStream in = conn.getInputStream();
String s = IOUtils.toString(in);
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
}

测试

下面的代码分别测试了不使用代理,设置全局代理,为单个连接设置代理3中情况。(测试代码中的代理为网上找的免费代理,比如:http://www.xicidaili.com/,响应速度,稳定性极差),如果代理无响应,java还会自动切换到本地请求

在上面的结果中有很多的异常,也有很多的本地请求(因为我目前所在地是在天津,切换本地请求就是天津)

注意了:代理服务器ip和端口都不是随便乱填的,是找的网上免费代理服务器

public static void main(String[] args) throws InterruptedException, IOException {
// 目标网址,会返回发起请求的ip
URL url1 = new URL("http://ip.chinaz.com/getip.aspx");
// 不设置任何代理
String result1 = printInputstream(url1.openStream());
System.out.println(" 不设置任何代理:" + result1); /**
* 方式一
*/
Properties prop = System.getProperties();
// 设置http访问要使用的代理服务器的地址
prop.setProperty("http.proxyHost", "120.35.30.178");
// 设置http访问要使用的代理服务器的端口
prop.setProperty("http.proxyPort", "80");
System.setProperties(prop);
URL url2 = new URL("http://ip.chinaz.com/getip.aspx");
String result2 = printInputstream(url2.openStream());
System.out.println(" 设置全局代理:" + result2); /**
* 方法二
*/
// 创建代理服务器
InetSocketAddress addr = new InetSocketAddress("220.202.127.78", 8118);
// http 代理
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
URL url3 = new URL("http://ip.chinaz.com/getip.aspx");
URLConnection conn = url3.openConnection(proxy);
conn.setReadTimeout(5000);
String result3 = printInputstream(conn.getInputStream());
System.out.println(" 为当前请求设置代理:" + result3);
} public static String printInputstream(InputStream in) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
reader = new BufferedReader(new InputStreamReader(in));
String s = null;
StringBuffer sb = new StringBuffer();
try {
while ((s = reader.readLine()) != null) {
sb.append(s);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}

测试完就会输出代理服务器的ip和所在地理位置,如果发现不行,那换一个服务器试试,http://www.xicidaili.com/


自动化操作

我们想达到刷访问量,刷票等需求的时候,不可能手动操作,那样会累死的,想刷100个访客或者100张票,那还得等刷到啥时候去了。

我们用http请求访问免费服务器,虽然有很多不能用,不能用的跳过,我们依然可以有很多的机会,更何况有好几千个免费代理服务器,况且还不断刷新,再说了,网上一大堆网站都分享免费服务器,慢归慢,卡归卡,但是免费呀,好了,废话不多说,看代码。

我们访问http请求得到相应的网页信息,但是我们要从中取出ip地址和端口号(得到网页String-->转换XML(dom4j)(更方便取)-->取代理服务器ip和端口)

其中用到了dom4j的jar包,maven贴上,

<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

Main.java

package com.xjh.xicidaili;

import com.xjh.demo.proxy.HttpClient;
import com.xjh.utils.HttpUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* Created by DIY on 2017/8/2.
*/
public class Main {
private static final String xicidaili = "http://www.xicidaili.com/nn";
public static void main(String args[]) throws IOException, DocumentException { long startTime = System.currentTimeMillis(); //开始时间 Map<String, String> headProperty = new HashMap<String, String>(); //请求头
// headProperty.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
// headProperty.put("Accept-Encoding", "gzip, deflate, sdch");
// headProperty.put("Accept-Language", "zh-CN,zh;q=0.8");
// headProperty.put("Connection", "keep-alive");
// headProperty.put("Host", "www.xicidaili.com");
// headProperty.put("If-None-Match", "W/\"971e6035d3280dcccdd49aa5a1e1d043\"");
// headProperty.put("Upgrade-Insecure-Requests", "1");
headProperty.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.101 Safari/537.36"); Map<String, String> requestProperty = new HashMap<String, String>(); //请求参数 HttpUtils httpUtil = new HttpUtils(xicidaili, headProperty, requestProperty);
httpUtil.setRequestMethod("GET"); //请求方式
HttpUtils.HttpResult xicidailiResult = httpUtil.request(); //同步请求
String xicidailiString = xicidailiResult.getResponseBodyString("UTF-8"); //开始dom4j解析
String table = xicidailiString.substring(xicidailiString.indexOf("<table"), xicidailiString.indexOf("</table>")+8); table.replaceAll("&lsaquo;", ""); //去掉非xml字符
Document document = DocumentHelper.parseText(table); //转换成xml //===开始从xml中获得想要的数据===
//获取xml文件的根节点
Element rootElement=document.getRootElement(); List elements = rootElement.elements(); //得到根节点下所有的子节点 //定义一个Element用于遍历
Element fooElement; //遍历所有名叫“VALUE”的节点
for(int e = 1 ; e<elements.size(); e++){
fooElement=(Element) elements.get(e); List list = fooElement.elements();
Element addressElement =(Element) list.get(1); //获得ip地址
Element portElement = (Element)list.get(2); //获得端口号
try {
HttpClient.httpRequest(addressElement.getText(), portElement.getText());
} catch (Exception e1) {
System.out.println(addressElement.getText() + "\t->\t异常");
}
} long endTime = System.currentTimeMillis();
System.out.println("耗时:"+ ((double)endTime - (double)startTime)/1000);
}
}

HttpUtils.java(这是个好东西啊)

package com.xjh.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set; /**
* Http简单封装类
* <p>
* 分为同步和异步请求
* <p>
*/
public class HttpUtils { private static final String TAG = "HttpUtils"; private static final boolean DEBUG = false; public final static String REQUEST_GET = "GET"; public final static String REQUEST_POST = "POST"; private String mRequestUrl = ""; private String mEncode = "utf-8"; /**
* 是否允许自动跳转 返回码为302的时候
*/
private boolean mAllowAutoJump = false; /**
* 是否取消了异步执行回调
*/
private boolean isCancel = false; /**
* 请求方式
*/
private String mRequestMethod = REQUEST_GET; /**
* 响应超时时间
*/
private int mTimeout = 1000 * 3; /**
* 请求头参数
*/
private Map<String, String> mHeadProperty = new HashMap<String, String>(); /**
* 请求参数
*/
private Map<String, String> mRequestProperty = new HashMap<String, String>(); public HttpUtils(String requestUrl) {
this(requestUrl, null);
} public HttpUtils(String requestUrl, Map<String, String> requestProperty) {
this(requestUrl, null, requestProperty);
} public HttpUtils(String requestUrl, Map<String, String> headProperty, Map<String, String> requestProperty) {
this.mRequestUrl = requestUrl;
this.mHeadProperty = headProperty;
this.mRequestProperty = requestProperty;
} /**
* 设置请求的URL
*/
public HttpUtils setRequestUrl(String url) {
this.mRequestUrl = url;
return this;
} /**
* 设置请求模式
*
* @param requestMethod {@link #REQUEST_GET} {{@link #REQUEST_POST}}
*/
public HttpUtils setRequestMethod(String requestMethod) {
this.mRequestMethod = requestMethod;
return this;
} /**
* 设置是否自动跳转,自动响应302等
*
* @param allow
* @return
*/
public HttpUtils setAllowAutoJump(boolean allow) {
mAllowAutoJump = allow;
return this;
} /**
* 设置请求头
*/
public HttpUtils setHeadProperty(Map<String, String> headProperty) {
this.mHeadProperty = headProperty;
return this;
} /**
* 添加请求头参数
*/
public HttpUtils addHeadProperty(String key, String value) {
this.mHeadProperty.put(key, value);
return this;
} /**
* 设置请求参数
*/
public HttpUtils setRequestProperty(Map<String, String> requestProperty) {
this.mRequestProperty = requestProperty;
return this;
} /**
* 添加请求参数
*/
public HttpUtils addRequestProperty(String key, String value) {
this.mRequestProperty.put(key, value);
return this;
} /**
* 设置超时时间
*/
public HttpUtils setTimeout(int timeout) {
this.mTimeout = timeout;
return this;
} /**
* 设置参数编码格式
*
* @param encoder 默认编码为utf-8
* @return
*/
public HttpUtils setRequestEncoder(String encoder) {
mEncode = encoder;
return this;
} /**
* 同步请求
*/
public HttpResult request() {
return doRequest();
} /**
* 取消异步请求
*/
public void cancelSync() {
isCancel = true;
} /**
* 发出异步请求
*/
public void requestSync(final HttpCallBack callBack) {
isCancel = false;
new Thread(new Runnable() {
@Override
public void run() {
HttpResult httpResult = doRequest();
//如果已经被取消掉了或者回调设置为空,则直接退出
if (isCancel || callBack == null) {
return;
}
if (httpResult.getException() != null) {
callBack.onError(httpResult.getException());
} else {
callBack.onSuccess(httpResult);
}
callBack.onComplete();
}
}).start();
} /**
* 在请求之前允许对请求进行处理
*
* @param headProperty 设置的请求头 可能为null
* @param requestProperty 设置的参数 可能为null
*/
protected void perRequest(Map<String, String> headProperty, Map<String, String> requestProperty) { } /**
* 允许对响应结果进行处理
*/
protected void afterRequest(HttpResult httpResult) { } /**
* 真正执行网络请求的位置
*/
private HttpResult doRequest() {
HttpResult httpResult = new HttpResult();
try {
//去掉网址结尾的 /分号
mRequestUrl.replaceAll("/*$", "");
perRequest(mHeadProperty, mRequestProperty);
URL url;
//请求参数格式化结果
String requestString = formatProperty(mRequestProperty);
if (REQUEST_GET.equals(mRequestMethod)) {
if ("".equals(requestString)) {
url = new URL(mRequestUrl);
} else {
url = new URL(mRequestUrl + "?" + requestString);
}
} else {
url = new URL(mRequestUrl);
}
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(mRequestMethod);
conn.setConnectTimeout(mTimeout);
conn.setReadTimeout(mTimeout);
conn.setInstanceFollowRedirects(mAllowAutoJump);
// conn.setAllowUserInteraction(mAllowAutoJump);
//设置请求头
if (mHeadProperty != null) {
Set<Map.Entry<String, String>> entries = mHeadProperty.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
conn.setRequestProperty(key, value);
}
}
//设置参数
if (REQUEST_POST.equals(mRequestMethod)) {
conn.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(requestString.getBytes(mEncode));
} InputStream in = conn.getInputStream();
byte[] responseBytes = inputStream2Bytes(in);
httpResult.setResponseCode(conn.getResponseCode());
httpResult.setResponseHead(conn.getHeaderFields());
httpResult.setResponseBody(responseBytes);
} catch (Exception e) {
httpResult.setException(e);
}
afterRequest(httpResult);
return httpResult;
} /**
* 格式化参数
* <p>
* 类似于pws=123&uid=123的形式
*/
private String formatProperty(Map<String, String> property) {
StringBuilder formatResult = new StringBuilder();
if (property == null) {
return formatResult.toString();
}
Set<Map.Entry<String, String>> entries = property.entrySet();
int begin = 0;
//拼接所有参数
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
if (begin == 0) {
begin++;
} else {
formatResult.append("&");
}
formatResult.append(key);
formatResult.append("=");
formatResult.append(value);
}
return formatResult.toString();
} /**
* 将输出流读取为字符串
*
* @param in 输出流
* @param charsetName 读取的编码格式
* @return
* @throws IOException
*/
private String inputStream2String(InputStream in, String charsetName) throws IOException {
StringBuffer result = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, charsetName));
String temp;
while ((temp = reader.readLine()) != null) {
result.append(temp);
}
in.close();
return result.toString();
} /**
* 将输入流装换为byte数组
*
* @param in 输入流
* @return
* @throws IOException
*/
private byte[] inputStream2Bytes(InputStream in) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
in.close();
return outStream.toByteArray();
} /**
* Http请求响应结果包装类
*/
public static final class HttpResult { private int mResponseCode; private Map<String, List<String>> mResponseHead; private byte[] mResponseBody; private Exception exception; public int getResponseCode() {
return mResponseCode;
} public void setResponseCode(int responseCode) {
this.mResponseCode = responseCode;
} public Map<String, List<String>> getResponseHead() {
return mResponseHead;
} public void setResponseHead(Map<String, List<String>> responseHead) {
this.mResponseHead = responseHead;
} public byte[] getResponseBody() {
return mResponseBody;
} public String getResponseBodyString(String charset) {
try {
return new String(getResponseBody(), charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
} public void setResponseBody(byte[] responseBody) {
this.mResponseBody = responseBody;
} public Exception getException() {
return exception;
} public void setException(Exception exception) {
this.exception = exception;
} @Override
public String toString() {
return "HttpResult{" +
"mResponseCode=" + mResponseCode +
", mResponseHead=" + mResponseHead +
", mResponseBody=" + Arrays.toString(mResponseBody) +
", exception=" + exception +
'}';
}
} /**
* Http响应回调
*/
public interface HttpCallBack { void onError(Exception e); void onSuccess(HttpResult httpResult); void onComplete();
}
}

HttpClient.java

package com.xjh.demo.proxy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Properties; /**
* Created by DIY on 2017/8/2.
*/
public class HttpClient { public static void httpRequest(String address, String port) throws Exception {
// 如果不设置,只要代理IP和代理端口正确,此项不设置也可以
// System.getProperties().setProperty("http.proxyHost", "10.22.40.32");
// System.getProperties().setProperty("http.proxyPort", "8080"); Properties prop = System.getProperties();
prop.setProperty("http.proxyHost", address);
prop.setProperty("http.proxyPort", port);
System.setProperties(prop);
// URL url2 = new URL("http://ip.chinaz.com/getip.aspx");
// String result2 = printInputstream(url2.openStream());
// System.out.println(" 设置全局代理:" + result2); // 判断代理是否设置成功
// 发送 GET 请求 System.out.println(sendGet(
"http://ip.chinaz.com/getip.aspx",
""));
// 发送 POST 请求
} /**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.print("发送GET请求出现异常!\t");
throw new RuntimeException("错误+1");
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} /**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} }

通过这样的操作,我们还不够,一个线程的力量是微小的,我们用多线程,分发线程,循环渐渐,我们想要的目的就达到了。

再或者我们可以用定时调度,有以下几种主要技术

1、Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务;

2、Quartz;

3、Spring3.0以后自带的task。

在每天定点定时的去访问我们的线程,这样我们可以完全放手让程序自己去跑,我们只需要偶尔看看它完成的好不好就ok的,这样服务器也会稍微轻松一点,这样也比较锻炼我们的技术与能力。

如果想关注spring的定时调度,请关注我的下一篇博文。

积木搭起的房子看似很美,

却会在不经意间轰然倒塌。

最新文章

  1. 领域驱动设计(DDD)部分核心概念的个人理解
  2. JSP自定义标签——调用数据库(通过id号搜索相关信息)
  3. IOS开发中与设计沟通之字体大小转换
  4. July 30th, Week 31st Saturday, 2016
  5. 一个小makefile程序
  6. 关于easyui模拟win2012桌面的一个例子系列
  7. Bootstrap+Thinkphp3.2+Auth认证+jquery-validator后台
  8. java面向对象之 继承 Inheritance
  9. HTML 5 服务器发送事件、Input 类型、表单元素、表单属性
  10. RHive
  11. ATmega8仿真——外部中断的学习
  12. linux-kernel-4.4 移植 (1)启动
  13. Android内存优化(四)LeakCanary使用详解
  14. vue-resource: jsonp请求百度搜索的接口
  15. c++ virtual 记录
  16. 对于League of Legends的分析
  17. git常用命令常用场景
  18. Ubuntu安装Chromium浏览器
  19. CSS快速入门-前端布局2(唯品会1)
  20. 互斥锁pthread_mutex_init()函数

热门文章

  1. BZOJ5018[Snoi2017]英雄联盟——DP
  2. day31 configparser 配置文件模块
  3. day29 上周复习
  4. 自学Linux Shell7.1-linux用户账户和组
  5. android 组件使用()
  6. [luogu3258][JLOI2014]松鼠的新家
  7. 51单片机 | I/O口直接输入输出实例
  8. 【uoj291】 ZJOI2017—树状数组
  9. 【洛谷P5018】对称二叉树
  10. 查询字符串(性能对比): Array Vs HashMap