最近在爬一些国外数据,需要挂代理请求一些网站,然而由于代理机器的验证问题,导致设置代理失败,几番面向搜索编程过后,发现Java自带一系统级对象,号曰:Authenticator,当你调用它的setDefault()时,你就已经成功了
上代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
public class AccessPasswordProtectedURLWithAuthenticator {
public static void main(String[] args) {
try {
// Sets the authenticator that will be used by the networking code
// when a proxy or an HTTP server asks for authentication.
Authenticator.setDefault(new CustomAuthenticator());
URL url = new URL("http://www.secure-site-example.com:80/");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
}
}
public static class CustomAuthenticator extends Authenticator {
// Called when password authorization is needed
protected PasswordAuthentication getPasswordAuthentication() {
// Get information about the request
String prompt = getRequestingPrompt();
String hostname = getRequestingHost();
InetAddress ipaddr = getRequestingSite();
int port = getRequestingPort();
String username = "username";
String password = "password";
// Return the information (a data holder that is used by Authenticator)
return new PasswordAuthentication(username, password.toCharArray());
}
}
}
正常我们如果没有什么特殊的需求,这么写就行
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password.toCharArray());
}
});
因为这个是系统级的,所以在所有请求发送前设置这个都是有效的,但我心里总有些不安,感觉好像有什么隐患。。。