81,094
社区成员
发帖
与我相关
我的任务
分享
import java.io.BufferedReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.InetAddress;
import java.net.PasswordAuthentication;
import java.net.URL;
public class AuthenticatorTest {
public static void main(String[] argv) throws Exception {
MyAuthenticator authenticator = new MyAuthenticator("username", "password");
Authenticator.setDefault(authenticator);
URL url = new URL("http://192.168.129.1:8002");
try {
InputStream in1 = url.openStream();
BufferedReader in = new BufferedReader(new InputStreamReader(in1, "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
if(authenticator.isAuthentError()){
System.out.println("用户名和密码错误,重新登录");
}else{
e.printStackTrace();
}
//System.err.println("aaaa");
}
}
}
class MyAuthenticator extends Authenticator {
private String name;
private String passwd;
private boolean authentError; //检查是否认证失败
public MyAuthenticator(String name, String passwd) {
this.name = name;
this.passwd = passwd;
}
protected PasswordAuthentication getPasswordAuthentication() {
String promptString = getRequestingPrompt();
String hostname = getRequestingHost();
InetAddress ipaddr = getRequestingSite();
if(promptString != null && hostname != null && ipaddr !=null){
authentError = true;
}
else{
authentError = false;
}
String username = name;
String password = passwd;
return new PasswordAuthentication(username, password.toCharArray());
}
public void setAuthentError(boolean authentError) {
this.authentError = authentError;
}
public boolean isAuthentError() {
return authentError;
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class URLTest {
public static void main(String[] args) {
URL url;
URLConnection urlconn;
try {
url = new URL("http://www.google.com.hk");
urlconn = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) urlconn;
InputStream in = httpConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in, "Big5"));
String line = "";
while((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
in.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}