Skip to content

Commit

Permalink
代理设置
Browse files Browse the repository at this point in the history
  • Loading branch information
dipoo committed Mar 23, 2016
1 parent d24cf91 commit 9839ac7
Show file tree
Hide file tree
Showing 12 changed files with 614 additions and 25 deletions.
14 changes: 14 additions & 0 deletions src/org/arong/egdownloader/db/impl/SettingDom4jDbTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.arong.egdownloader.db.DbTemplate;
import org.arong.egdownloader.model.Setting;
import org.arong.egdownloader.ui.ComponentConst;
import org.arong.util.CodeUtil;
import org.arong.util.Dom4jUtil;
import org.arong.util.FileUtil;
import org.dom4j.Document;
Expand Down Expand Up @@ -218,6 +220,12 @@ private Element setting2Element(Setting t) {
ele.addAttribute("collectPictureScriptPath", t.getCollectPictureScriptPath());
ele.addAttribute("downloadScriptPath", t.getDownloadScriptPath());
ele.addAttribute("searchScriptPath", t.getSearchScriptPath());

ele.addAttribute("useProxy", t.isUseProxy() + "");
ele.addAttribute("proxyIp", t.getProxyIp());
ele.addAttribute("proxyPort", t.getProxyPort());
ele.addAttribute("proxyUsername", t.getProxyUsername());
ele.addAttribute("proxyPwd", CodeUtil.myEncode(t.getProxyPwd()));
return ele;
}
private Setting node2Setting(Node node) {
Expand Down Expand Up @@ -282,6 +290,12 @@ private Setting node2Setting(Node node) {
t.setCollectPictureScriptPath(ele.attributeValue("collectPictureScriptPath") == null ? t.getCollectPictureScriptPath() : ele.attributeValue("collectPictureScriptPath"));
t.setDownloadScriptPath(ele.attributeValue("downloadScriptPath") == null ? t.getDownloadScriptPath() : ele.attributeValue("downloadScriptPath"));
t.setSearchScriptPath(ele.attributeValue("searchScriptPath") == null ? t.getSearchScriptPath() : ele.attributeValue("searchScriptPath"));

t.setUseProxy("true".equals(ele.attributeValue("useProxy")) ? true : false);
t.setProxyIp(ele.attributeValue("proxyIp"));
t.setProxyPort(ele.attributeValue("proxyPort"));
t.setProxyUsername(ele.attributeValue("proxyUsername"));
t.setProxyPwd(CodeUtil.myDecode(ele.attributeValue("proxyPwd")));
return t;
}

Expand Down
40 changes: 40 additions & 0 deletions src/org/arong/egdownloader/model/Setting.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ public class Setting {
private String lastDownloadTime;//最后下载时间
private String lastCreateTime;//最后创建时间

/**
* 代理
*/
private boolean useProxy = false;//是否使用代理
private String proxyIp;//代理ip
private String proxyPort;//代理端口
private String proxyUsername;//代理用户名
private String proxyPwd;//代理密码



public String[] getTask_name() {
return task_name;
Expand Down Expand Up @@ -342,4 +352,34 @@ public void setUpdateScriptWorker(UpdateScriptWorker updateScriptWorker) {
public UpdateScriptWorker getUpdateScriptWorker() {
return updateScriptWorker;
}
public boolean isUseProxy() {
return useProxy;
}
public void setUseProxy(boolean useProxy) {
this.useProxy = useProxy;
}
public String getProxyIp() {
return proxyIp;
}
public void setProxyIp(String proxyIp) {
this.proxyIp = proxyIp;
}
public String getProxyPort() {
return proxyPort;
}
public void setProxyPort(String proxyPort) {
this.proxyPort = proxyPort;
}
public String getProxyUsername() {
return proxyUsername;
}
public void setProxyUsername(String proxyUsername) {
this.proxyUsername = proxyUsername;
}
public String getProxyPwd() {
return proxyPwd;
}
public void setProxyPwd(String proxyPwd) {
this.proxyPwd = proxyPwd;
}
}
140 changes: 140 additions & 0 deletions src/org/arong/egdownloader/spider/Proxy.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package org.arong.egdownloader.spider;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
/**
* 代理
* @author dipoo
* @since 2016-03-22
*/
public class Proxy {
public static boolean useProxy;
public static String ip;
public static String port;
public static String username;
public static String pwd;

public static void init(boolean useProxy_, String ip_, String port_, String username_, String pwd_){
useProxy = useProxy_;
ip = ip_;
port = port_;
username = username_;
pwd = pwd_;
//proxy();
}

/**
* jvm全局使用代理
*/
public static void proxy(){
if(useProxy){
System.setProperty("http.maxRedirects", "50");
System.getProperties().setProperty("proxySet", "true");
System.getProperties().setProperty("http.proxyHost", ip);
System.getProperties().setProperty("http.proxyPort", port);
}else{
System.getProperties().setProperty("proxySet", "false");
System.getProperties().setProperty("http.proxyHost", "");
System.getProperties().setProperty("http.proxyPort", "");
}
}

/**
* 取消jvm全局代理
*/
public static void unproxy(){
if(!useProxy){
System.getProperties().setProperty("proxySet", "false");
}
}

public static HttpClient getHttpClient(){
HttpClient httpClient = new HttpClient();
if(useProxy){
//设置代理服务器的ip地址和端口
httpClient.getHostConfiguration().setProxy(ip, Integer.parseInt(port));
//使用抢先认证
httpClient.getParams().setAuthenticationPreemptive(true);
//如果代理需要密码验证,这里设置用户名密码
if(username != null && pwd != null){
httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, pwd));
}
}
return httpClient;
}

public static java.net.Proxy getNetProxy(){
if(useProxy){
return new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(ip, Integer.parseInt(port)));
}
return null;
}

public static void main(String[] args) throws IOException {
System.setProperty("http.maxRedirects", "50");
System.getProperties().setProperty("proxySet", "true");
// 如果不设置,只要代理IP和代理端口正确,此项不设置也可以
String ip = "127.0.0.1";
/*ip = "221.130.18.5";
ip = "221.130.23.135";
ip = "221.130.18.78";
ip = "221.130.23.134";
ip = "221.130.18.49";
ip = "111.1.32.36";
ip = "221.130.18.49";
ip = "221.130.18.49";*/
System.getProperties().setProperty("http.proxyHost", ip);
System.getProperties().setProperty("http.proxyPort", "22900");

//确定代理是否设置成功
System.out.println(getHtml("http://1212.ip138.com/ic.asp"));

}

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;
}

public boolean isUseProxy() {
return useProxy;
}
}
86 changes: 75 additions & 11 deletions src/org/arong/egdownloader/spider/WebClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
* 获取远程url地址页面的源文件
Expand Down Expand Up @@ -63,7 +65,7 @@ public static String postRequestWithCookie(String url, String cookieInfo) throws
* @throws SocketTimeoutException
*/
public static String postRequestWithCookie(String url, String encoding, Map<String, String> rawParams, String cookieInfo) throws WebClientException, ConnectTimeoutException, SocketTimeoutException {
HttpClient httpClient = new HttpClient();
HttpClient httpClient = Proxy.getHttpClient();
// 创建HttpPost对象。
PostMethod postMethod = new PostMethod(url);
postMethod.setDoAuthentication(true);
Expand Down Expand Up @@ -98,6 +100,7 @@ public static String postRequestWithCookie(String url, String encoding, Map<Stri
// 如果服务器成功地返回响应
if (statusCode == 200 || statusCode == 201) {
// 获取服务器响应字符串
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
result = postMethod.getResponseBodyAsString();
}else if (statusCode == 302) {
// 重定向
Expand Down Expand Up @@ -142,7 +145,7 @@ public static String getCookieByPostWithoutCookie(String url, String encoding, M
* @throws SocketTimeoutException
*/
public static String getCookieByPostWithCookie(String url, String encoding, Map<String, String> rawParams, String cookieInfo) throws WebClientException, ConnectTimeoutException, SocketTimeoutException {
HttpClient httpClient = new HttpClient();
HttpClient httpClient = Proxy.getHttpClient();
// 创建HttpPost对象。
PostMethod postMethod = new PostMethod(url);
postMethod.setDoAuthentication(true);
Expand Down Expand Up @@ -244,7 +247,7 @@ public static InputStream postRequestAsStreamWithCookie(String url, String cooki
* @throws SocketTimeoutException
*/
public static InputStream postRequestAsStreamWithCookie(String url, String encoding, Map<String, String> rawParams, String cookieInfo) throws WebClientException, ConnectTimeoutException, SocketTimeoutException {
HttpClient httpClient = new HttpClient();
HttpClient httpClient = Proxy.getHttpClient();
// 创建HttpPost对象。
PostMethod postMethod = new PostMethod(url);
postMethod.setDoAuthentication(true);
Expand Down Expand Up @@ -318,8 +321,21 @@ public static InputStream getStreamUseJava(final String urlString)

try{
do {
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
HttpURLConnection urlConnection = null;
if(Proxy.getNetProxy() != null){
urlConnection = (HttpURLConnection) url
.openConnection(Proxy.getNetProxy());
if(Proxy.username != null && Proxy.pwd != null){
//格式如下:
//"Proxy-Authorization"= "Basic Base64.encode(user:password)"
String headerKey = "Proxy-Authorization";
String headerValue = "Basic " + Base64.encodeBase64((Proxy.username+":"+Proxy.pwd).getBytes());
urlConnection.setRequestProperty(headerKey, headerValue);
}
}else{
urlConnection = (HttpURLConnection) url
.openConnection();
}
// 添加访问授权
if (digest != null) {
urlConnection.setRequestProperty("Authorization", digest);
Expand All @@ -332,7 +348,7 @@ public static InputStream getStreamUseJava(final String urlString)
urlConnection.setConnectTimeout(20000);
urlConnection.setReadTimeout(20000);
//模拟http头文件
urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0;)");
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36");
urlConnection.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
//追加http头文件
Set<Entry<String, String>> headersSet = headers.entrySet();
Expand All @@ -357,6 +373,27 @@ public static InputStream getStreamUseJava(final String urlString)
} else {
if (responseCode == 200 || responseCode == 201) {
inputStream = urlConnection.getInputStream();
}else{
// 获得返回的数据长度
int responseLength = urlConnection.getContentLength();
BufferedInputStream in;
if (responseCode == 200 || responseCode == 201) {
in = new BufferedInputStream(urlConnection.getInputStream());
} else {
in = new BufferedInputStream(urlConnection.getErrorStream());
}
int size = responseLength == -1 ? 4096 : responseLength;
String responseContent = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] bytes = new byte[size];
int read;
while ((read = in.read(bytes)) >= 0) {
out.write(bytes, 0, read);
}
responseContent = new String(out.toByteArray());
in.close();
out.close();
System.out.println(responseContent);
}
foundRedirect = false;
}
Expand Down Expand Up @@ -404,9 +441,23 @@ public static String getRequestUseJava(final String urlString,

try{
do {

HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();

HttpURLConnection urlConnection = null;
if(Proxy.getNetProxy() != null){
urlConnection = (HttpURLConnection) url
.openConnection(Proxy.getNetProxy());
if(Proxy.username != null && Proxy.pwd != null){
//格式如下:
//"Proxy-Authorization"= "Basic Base64.encode(user:password)"
String headerKey = "Proxy-Authorization";
String headerValue = "Basic " + Base64.encodeBase64((Proxy.username+":"+Proxy.pwd).getBytes());
urlConnection.setRequestProperty(headerKey, headerValue);
}
}else{
urlConnection = (HttpURLConnection) url
.openConnection();
}

// 添加访问授权
if (digest != null) {
urlConnection.setRequestProperty("Authorization", digest);
Expand Down Expand Up @@ -503,8 +554,21 @@ public static String getCookieUseJava(final String urlString,
try{
do {

HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
HttpURLConnection urlConnection = null;
if(Proxy.getNetProxy() != null){
urlConnection = (HttpURLConnection) url
.openConnection(Proxy.getNetProxy());
if(Proxy.username != null && Proxy.pwd != null){
//格式如下:
//"Proxy-Authorization"= "Basic Base64.encode(user:password)"
String headerKey = "Proxy-Authorization";
String headerValue = "Basic " + Base64.encodeBase64((Proxy.username+":"+Proxy.pwd).getBytes());
urlConnection.setRequestProperty(headerKey, headerValue);
}
}else{
urlConnection = (HttpURLConnection) url
.openConnection();
}
// 添加访问授权
if (digest != null) {
urlConnection.setRequestProperty("Authorization", digest);
Expand Down
Loading

0 comments on commit 9839ac7

Please sign in to comment.