/**
* Copyright (c) 2012 Trusted Software and Mobile Computing(TSMC)
* All right reserved.
*
* Created on Apr 24, 2012 12:42:24 PM
* http://jarg.iteye.com/
* Author: Jarg Yee <yeshaoting@gmail.com>
*/
package com.iteye.jarg.monitor.test;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
/**
* TODO 使用代理服务器工具类
*/
public class ProxyUtil
{
/** 代理服务器IP地址 e.g. 10.10.0.96 */
private static final String IP = "10.10.0.96";
/** 初始化代理 */
public static void initProxy()
{
Properties prop = System.getProperties();
// 设置http访问要使用的代理服务器的地址
prop.setProperty("http.proxyHost", IP);
// 设置http访问要使用的代理服务器的端口
prop.setProperty("http.proxyPort", "808");
// 设置不需要通过代理服务器访问的主机,可以使用*通配符,多个地址用|分隔
prop.setProperty("http.nonProxyHosts", "localhost|10.10.*");
// 设置安全访问使用的代理服务器地址与端口
// 它没有https.nonProxyHosts属性,它按照http.nonProxyHosts 中设置的规则访问
prop.setProperty("https.proxyHost", IP);
prop.setProperty("https.proxyPort", "443");
// 使用ftp代理服务器的主机、端口以及不需要使用ftp代理服务器的主机
prop.setProperty("ftp.proxyHost", IP);
prop.setProperty("ftp.proxyPort", "2121");
prop.setProperty("ftp.nonProxyHosts", "localhost|10.10.*");
// socks代理服务器的地址与端口
prop.setProperty("socksProxyHost", IP);
prop.setProperty("socksProxyPort", "1080");
}
/**
* 使用代理
* */
private static void testProxy() throws IOException
{
/** 使用代理连接网络 */
URL url = new URL("http://www.baidu.com/");
URLConnection conn = url.openConnection();
conn.setConnectTimeout(3000);
InputStream in = conn.getInputStream();
BufferedInputStream bin = new BufferedInputStream(in);
byte[] buf = new byte[1024]; // 缓存连网获得的数据
while(bin.read(buf) > 0)
{
System.out.print(new String(buf, "GBK"));
}
System.out.println();
}
/** for debugging.
* @throws IOException */
public static void main(String[] args) throws IOException
{
initProxy(); // 初始化代理
testProxy(); // 使用代理
}
}