访问受密码保护的URL

时间:2015-09-14 19:51:43

标签: android authentication

我试图访问需要通过用户名和密码进行身份验证的网址。

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

这是第一个类,它设置将由网络代码

使用的验证器
 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());

    }

}

}

第二课

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

    }

}

4 个答案:

答案 0 :(得分:3)

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

Authenticator.setDefault(new CustomAuthenticator());

答案 1 :(得分:2)

您是否尝试过将用户名和密码添加到URL本身的主机名中?这可能允许您完全避免使用Authenticator:

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

答案 2 :(得分:1)

这可能很方便。

private HttpURLConnection getJsonConnection(String urlString) throws IOException {

    URL url = new URL(urlString);

    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

    String userCredentials = "username:password";
    String basicAuth = "Basic " + Base64.encodeToString(userCredentials.getBytes(), Base64.DEFAULT);
    urlConnection.setRequestProperty("Authorization", basicAuth);


    return urlConnection;
}

private String getResponse(HttpURLConnection urlConnection) throws IOException {

    BufferedReader bufferedReader = null;

    try {

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

            bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = bufferedReader.readLine()) != null) {
                response.append(inputLine);
            }

            return response.toString();
        }

    } catch (IOException e) {

        Logger.error(e);

    } finally {

        if (bufferedReader != null) {
            bufferedReader.close();
        }
    }
    return null;
}

答案 3 :(得分:0)

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 Main {
  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 = "Administrator";
    String password = "Administrator";
    return new PasswordAuthentication(username, password.toCharArray());
  }
}

检查以上示例是否适用于您