您的位置:首页 > 编程语言 > Java开发

java 设置代理ip

2016-05-17 10:23 489 查看
java有两种方法可以设置代理ip,简单介绍一下优劣

第一种,直接在JVM中设置:

/*JVM设置代理*/
System.getProperties().setProperty("http.proxyHost", ip);
System.getProperties().setProperty("http.proxyPort", "80");


这种设置的优势是快捷方便,且由于是JVM级别的设置,可以对整个项目起作用。当然这种设置方法有一个明显的劣势:当代理ip不可用时,会直接调用本地网络来进行连接。这个问题在很多使用场景中是非常致命的。

第二种,使用SocketAddress网络代理

/**
* 通过代理对象连接
* @param address
* @return
*/
SocketAddress addr = new InetSocketAddress(host, Integer.parseInt(port));
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
try{
URL url = new URL("http://www.baidu.com");
URLConnection conn = url.openConnection(proxy);
conn.setConnectTimeout(5000);
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; NT 5.1; GTB5; .NET CLR 2.0.50727; CIBA)");
conn.getContent();
}catch (Exception e) {
e.printStackTrace();
}


建立一个Proxy对象,然后使用这个对象来进行连接。当代理失效时,会直接抛出异常。这种办法的优势是,在代理连接发生错误时,会抛出异常而并不是使用本地的连接继续访问。而劣势也很明显,你需要为每一次连接创建一个代理对象。

最后是一个用于验证代理IP是否生效的抓取程序,抓取地址是:http://1212.ip138.com/ic.asp 可以直接看到访问的ip地址。需要注意的是,如果你使用的是透明代理,那么这个ip依然会显示为你的实际ip只有使用匿名代理时,该ip才会变成代理ip。

以下是抓取程序:

/**
* 获得页面信息
* @param address
* @return
*/
private static String getHtml(String address){
StringBuffer html = new StringBuffer();
String result = null;
try{
URL url = new URL(address);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 7.0; NT 5.1; GTB5; .NET CLR 2.0.50727; CIBA)");
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

try{
String inputLine;
byte[] buf = new byte[4096];
int bytesRead = 0;
while (bytesRead >= 0) {
inputLine = new String(buf, 0, bytesRead, "ISO-8859-1");
html.append(inputLine);
bytesRead = in.read(buf);
inputLine = null;
}
buf = null;
}finally{
in.close();
conn = null;
url = null;
}
result = new String(html.toString().trim().getBytes("ISO-8859-1"), "gb2312").toLowerCase();

}catch (Exception e) {
e.printStackTrace();
return null;
}finally{
html = null;
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java