访问受密码保护的URL

Wee*_*ees 9 authentication android

我正在尝试访问需要通过用户名和密码进行身份验证的网址.

建设时没有错误..我错过了什么吗?

这是第一个类,它设置将由网络代码使用的验证器

 public class AccessPasswordProtectedURLWithAuthenticator {

  public static void main(String[] args) {

    try {

        // when a proxy or an HTTP server asks for authentication.

        Authenticator.setDefault(new Authenticator(){});

        URL url = new URL("http://website.html");

        // 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());

    }

}

}
Run Code Online (Sandbox Code Playgroud)

第二节课

 public 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 = "Administrator";

        String password = "Administrator";

        /// Return the information (a data holder that is used by Authenticator)

        return new PasswordAuthentication(username, password.toCharArray());

    }

}
Run Code Online (Sandbox Code Playgroud)

gla*_*ded 3

您的第一个代码段不引用第二个类。它应该有这样的代码:

Authenticator.setDefault(new CustomAuthenticator());
Run Code Online (Sandbox Code Playgroud)