0%

java获取需要HTTP验证的网页内容

其实代码都差不多,就是加上发送帐号密码的一段。

        try {
            URL newurl = new URL(url);		
            Authenticator auth = new Authenticator() {   
                private PasswordAuthentication pa =    
                    new PasswordAuthentication("username", "password".toCharArray());   
                @Override  
                protected PasswordAuthentication getPasswordAuthentication() {   
                    return pa;   
                }   
            };   
            Authenticator.setDefault(auth);   
                
            BufferedReader br = new BufferedReader(new InputStreamReader(newurl.openStream()));  
            String s = "";  
            StringBuffer sb = new StringBuffer("");  

            while ((s = br.readLine()) != null) {  
                sb.append(s + "\r\n");  

            }  
            br.close(); 
            String s1=sb.toString(); 
            byte[] bs=s1.getBytes();
            s1=new String(bs,"UTF-8");
            return  s1;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            return "error open url:" + url;  
        }