日期:2014-05-20 浏览次数:20983 次
import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public static void testConnect(String surl) throws IOException { URL url = new URL(surl); String userInfo = url.getUserInfo(); if (userInfo != null && userInfo.length() > 0) { String string = surl.replace(userInfo, ""); url = new URL(string); } URLConnection connection = (HttpURLConnection) url.openConnection(); if (userInfo != null && userInfo.length() > 0) connection.setRequestProperty("Authorization", userInfo); connection.connect(); } public static void main(String args[]) throws IOException{ String url = "http://192.9.168.11:1122/";//http://user:pass@192.9.168.11:1122/ testConnect(url); }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.InetAddress; import java.net.PasswordAuthentication; import java.net.URL; public class Test { public static void main(String[] argv) throws Exception { Authenticator.setDefault(new MyAuthenticator()); URL url = new URL("http://hostname:80/index.html"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { System.out.println(str); } in.close(); } } class MyAuthenticator extends Authenticator { protected PasswordAuthentication getPasswordAuthentication() { String promptString = getRequestingPrompt(); System.out.println(promptString); String hostname = getRequestingHost(); System.out.println(hostname); InetAddress ipaddr = getRequestingSite(); System.out.println(ipaddr); int port = getRequestingPort(); String username = "name"; String password = "password"; return new PasswordAuthentication(username, password.toCharArray()); } }