如何连接到需要身份验证的Java远程URL.我试图找到一种方法来修改以下代码,以便能够以编程方式提供用户名/密码,因此它不会抛出401.
URL url = new URL(String.format("http://%s/manager/list", _host + ":8080")); HttpURLConnection connection = (HttpURLConnection)url.openConnection();
James Van Hu.. 127
您可以为http请求设置默认验证器,如下所示:
Authenticator.setDefault (new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication ("username", "password".toCharArray()); } });
此外,如果您需要更多灵活性,可以查看Apache HttpClient,它将为您提供更多身份验证选项(以及会话支持等)
您可以为http请求设置默认验证器,如下所示:
Authenticator.setDefault (new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication ("username", "password".toCharArray()); } });
此外,如果您需要更多灵活性,可以查看Apache HttpClient,它将为您提供更多身份验证选项(以及会话支持等)
这是一种原生的,不那么具有侵入性的选择,仅适用于您的通话.
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();
您还可以使用以下内容,不需要使用外部包:
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();
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();
当我来到这里寻找Android-Java-Answer时,我将做一个简短的总结:
使用James van Huis所示的java.net.Authenticator
使用Apache Commons HTTP Client,如本答案中所述
使用基本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