下面是一个下载代理类:有带验证的代理及不待验证的代理,也可以选择直连不使用代理,很详细了。。。。
/**
* 提供一个得到 URLConnection 类,调用函数为: getUrl(String urlStr,String proxyAddress,int proxyPort);* @author Janus
*
*/
public class DownloadProxy{
private static String isProxyOn=null; // 是否开启代理
private static Proxy proxy = null; // 代理对象
private static String username = null; // 代理用户名
private static String password = null; // 代理的密码
private static String proxyAddress = null; // 代理服务器地址
private static int proxyPort; // 代理服务器端口号
/**
* 构造函数私有,该类不可实例化
*/
private DownloadProxy(){
}
/**
* 通过配置类获取代理的配置信息并初始化代理
*/
public static void initProxy() {
isProxyOn=Configuration.getPropertiesByKey("isProxyOn");
proxyAddress=Configuration.getPropertiesByKey("proxyHost");
proxyPort=Integer.parseInt(Configuration.getPropertiesByKey("proxyPort"));
username=Configuration.getPropertiesByKey("username");
password=Configuration.getPropertiesByKey("password");
//初始化代理
proxy=new Proxy(Proxy.Type.HTTP,new InetSocketAddress(proxyAddress,proxyPort));
}
/**
* @param url
* 该方法返回一个HttpURLConnection
*/
public static HttpURLConnection getConnection(String url) throws IOException {
URL Url =new URL(url); //下载资源的URL
HttpURLConnection conn=null; //请求连接
if(isProxyOn.equals("true")) {
if(username==null||password==null){
//不带验证代理
conn=(HttpURLConnection)Url.openConnection(proxy);
conn.setConnectTimeout(5000);
return conn;
}else{
//带验证代理
sun.misc.BASE64Encoder B64 = new sun.misc.BASE64Encoder();
conn = (HttpURLConnection)Url.openConnection(proxy);
String headerKey="Proxy-Authorization";
String headerValue="Basic "+B64.encode(new String(username+":"+password).getBytes()).replaceAll("\n", "");
conn.setRequestProperty(headerKey, headerValue);
conn.setConnectTimeout(5000);
return conn;
}
} else {
//未开启代理,直连
conn= (HttpURLConnection)new URL(url).openConnection();conn.setConnectTimeout(5000);
return conn;
}
}
}