集册 Java实例教程 访问密码

访问密码

欢马劈雪     最近更新时间:2020-01-02 10:19:05

383
访问受密码保护的URL
// 来 自 N o w J a v a . c o m - 时  代  Java

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 Main {

  public static void main(String[] argv) {

    Authenticator.setDefault(new MyAuthenticator());


    try {

      URL url = new URL("http://hostname:80/index.html");
      /** 
      来 自 
      n o w j a v a . c o m - 时代Java
      **/


      BufferedReader in = new BufferedReader(new InputStreamReader(

          url.openStream()));

      String str;

      while ((str = in.readLine()) != null) {

        // str is one line of text; readLine() strips the newline character(s)

      }

      in.close();

    } catch (MalformedURLException e) {

    } catch (IOException e) {

    }

  }


}


class MyAuthenticator extends Authenticator {

  protected PasswordAuthentication getPasswordAuthentication() {

    // Get information about the request

    String promptString = getRequestingPrompt();

    String hostname = getRequestingHost();

    InetAddress ipaddr = getRequestingSite();

    int port = getRequestingPort();


    // Get the username from the user...

    
展开阅读全文