Skip to content

Commit 89c6e52

Browse files
committed
代理增加用户名密码认证
1 parent 047cb8f commit 89c6e52

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

webmagic-core/src/main/java/us/codecraft/webmagic/Site.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import com.google.common.collect.Table;
55
import org.apache.http.HttpHost;
66

7+
import org.apache.http.auth.UsernamePasswordCredentials;
78
import us.codecraft.webmagic.proxy.ProxyPool;
89
import us.codecraft.webmagic.utils.UrlUtils;
910

@@ -51,6 +52,8 @@ public class Site {
5152

5253
private HttpHost httpProxy;
5354

55+
private UsernamePasswordCredentials usernamePasswordCredentials; //代理用户名密码设置
56+
5457
private ProxyPool httpProxyPool;
5558

5659
private boolean useGzip = true;
@@ -479,6 +482,15 @@ public Site enableHttpProxyPool() {
479482
return this;
480483
}
481484

485+
public UsernamePasswordCredentials getUsernamePasswordCredentials() {
486+
return usernamePasswordCredentials;
487+
}
488+
489+
public Site setUsernamePasswordCredentials(UsernamePasswordCredentials usernamePasswordCredentials) {
490+
this.usernamePasswordCredentials = usernamePasswordCredentials;
491+
return this;
492+
}
493+
482494
public ProxyPool getHttpProxyPool() {
483495
return httpProxyPool;
484496
}

webmagic-core/src/main/java/us/codecraft/webmagic/downloader/HttpClientGenerator.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
import org.apache.http.HttpException;
44
import org.apache.http.HttpRequest;
55
import org.apache.http.HttpRequestInterceptor;
6+
import org.apache.http.auth.AuthScope;
7+
import org.apache.http.auth.UsernamePasswordCredentials;
68
import org.apache.http.client.CookieStore;
9+
import org.apache.http.client.CredentialsProvider;
710
import org.apache.http.config.Registry;
811
import org.apache.http.config.RegistryBuilder;
912
import org.apache.http.config.SocketConfig;
@@ -65,6 +68,15 @@ public void process(
6568
}
6669
});
6770
}
71+
72+
if(site!=null&&site.getHttpProxy()!=null&&site.getUsernamePasswordCredentials()!=null){
73+
CredentialsProvider credsProvider = new BasicCredentialsProvider();
74+
credsProvider.setCredentials(
75+
new AuthScope(site.getHttpProxy()),//可以访问的范围
76+
site.getUsernamePasswordCredentials());//用户名和密码
77+
httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
78+
}
79+
6880
SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
6981
httpClientBuilder.setDefaultSocketConfig(socketConfig);
7082
if (site != null) {

0 commit comments

Comments
 (0)