连接到需要使用Java进行身份验证的远程URL

use*_*128 119 java httpurlconnection

如何连接到需要身份验证的Java远程URL.我试图找到一种方法来修改以下代码,以便能够以编程方式提供用户名/密码,因此它不会抛出401.

URL url = new URL(String.format("http://%s/manager/list", _host + ":8080"));
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
Run Code Online (Sandbox Code Playgroud)

Jam*_*uis 127

您可以为http请求设置默认验证器,如下所示:

Authenticator.setDefault (new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("username", "password".toCharArray());
    }
});
Run Code Online (Sandbox Code Playgroud)

此外,如果您需要更多灵活性,可以查看Apache HttpClient,它将为您提供更多身份验证选项(以及会话支持等)

  • 是否可以为每个特定的`URL.openConnection()调用设置特定的`Authenticator`而不是全局设置? (12认同)
  • 你如何处理错误的身份验证事件?[例如,如果用户提供与任何内容不匹配的用户名和密码身份验证凭据]? (4认同)
  • 响应@YuriyNakonechnyy ...如果您使用的是Java 9或更高版本,则可以调用`HttpURLConnection.setAuthenticator()`。不幸的是,在Java 8和更早版本中,Authenticator实例是JVM范围的全局变量。参见:https://docs.oracle.com/javase/9​​/docs/api/java/net/HttpURLConnection.html#setAuthenticator-java.net.Authenticator- (3认同)
  • 上面的代码可以工作,但是对于最新的内容是非常隐含的.那里有子类化和方法覆盖,如果你想知道发生了什么,请深入研究这些类的文档.这里的代码更明确[javacodegeeks](http://examples.javacodegeeks.com/core-java/net/authenticator/access-password-protected-url-with-authenticator/) (2认同)

Wan*_*tos 127

这是一种原生的,不那么具有侵入性的选择,仅适用于您的通话.

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();
Run Code Online (Sandbox Code Playgroud)

  • Base64类可以由Apache Commons Codec提供. (5认同)

小智 77

您还可以使用以下内容,不需要使用外部包:

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();
Run Code Online (Sandbox Code Playgroud)

  • 我一直在寻找Java标准包内的Base64编码器这么久!谢谢 (10认同)
  • 感谢指向"原生"Base64编码器的指针! (8认同)

jav*_*der 39

If you are using the normal login whilst entering the username and password between the protocol and the domain this is simpler. It also works with and without login.

Sample Url: http://user:pass@domain.com/url

URL url = new URL("http://user:pass@domain.com/url");
URLConnection urlConnection = url.openConnection();

if (url.getUserInfo() != null) {
    String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
    urlConnection.setRequestProperty("Authorization", basicAuth);
}

InputStream inputStream = urlConnection.getInputStream();
Run Code Online (Sandbox Code Playgroud)


Dan*_*Ell 8

当我来到这里寻找Android-Java-Answer时,我将做一个简短的总结:

  1. 使用James van Huis所示的java.net.Authenticator
  2. 使用Apache Commons HTTP Client,如本答案中所述
  3. 使用基本java.net.URLConnection中并手动设置认证报头所示一样在这里

如果你想在Android中使用带有基本身份验证的java.net.URLConnection,请尝试以下代码:

URL url = new URL("http://www.mywebsite.com/resource");
URLConnection urlConnection = url.openConnection();
String header = "Basic " + new String(android.util.Base64.encode("user:pass".getBytes(), android.util.Base64.NO_WRAP));
urlConnection.addRequestProperty("Authorization", header);
// go on setting more request headers, reading the response, etc
Run Code Online (Sandbox Code Playgroud)


Tim*_*Tim 7

能够使用 HttpsURLConnection 设置身份验证

           URL myUrl = new URL(httpsURL);
            HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
            String userpass = username + ":" + password;
            String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
            //httpsurlconnection
            conn.setRequestProperty("Authorization", basicAuth);
Run Code Online (Sandbox Code Playgroud)

从这篇文章中提取的更改很少。Base64 来自 java.util 包。


lbo*_*oix 5

使用“Base64().encode()”方法时要非常小心,我和我的团队遇到了 400 个 Apache 错误请求问题,因为它在生成的字符串末尾添加了 \r\n。

感谢 Wireshark,我们发现它可以嗅探数据包。

这是我们的解决方案:

import org.apache.commons.codec.binary.Base64;

HttpGet getRequest = new HttpGet(endpoint);
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding());

private String getBasicAuthenticationEncoding() {

        String userPassword = username + ":" + password;
        return new String(Base64.encodeBase64(userPassword.getBytes()));
    }
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!