问题
如何连接到需要身份验证的Java远程URL。我正在尝试找到一种方法来修改以下代码,以便能够以编程方式提供用户名/密码,因此它不会抛出401。
URL url = new URL(String.format("http://%s/manager/list", _host + ":8080"));
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
#1 热门回答(120 赞)
你可以为http请求设置默认验证器,如下所示:
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});
此外,如果你需要更多灵活性,可以查看Apache HttpClient,它将为你提供更多身份验证选项(以及会话支持等)
#2 热门回答(97 赞)
这是一种原生的,不那么具有侵入性的选择,仅适用于你的通话。
URL url = new URL("location address");
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
#3 热门回答(68 赞)
你还可以使用以下内容,不需要使用外部包:
URL url = new URL("location address");
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();