如何连接到需要身份验证的Java远程URL。我试图找到一种方法来修改以下代码,以便能够以编程方式提供用户名/密码,因此它不会抛出401.
URL url = new URL(String.format("http://%s/manager/list", _host + ":8080"));
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
答案 0 :(得分:125)
您可以为http请求设置默认身份验证器,如下所示:
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});
此外,如果您需要更多灵活性,可以查看Apache HttpClient,这将为您提供更多身份验证选项(以及会话支持等)。
答案 1 :(得分:114)
这是一种原生的,不那么具有干扰性的选择,仅适用于您的通话。
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();
答案 2 :(得分:78)
您还可以使用以下内容,不需要使用外部包:
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();
答案 3 :(得分:37)
如果您在协议和域之间输入用户名和密码时使用正常登录,则这更简单。它也适用于登录和不登录。
示例网址: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();
答案 4 :(得分:8)
当我来到这里寻找Android-Java-Answer时,我将做一个简短的总结:
如果您想在 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
答案 5 :(得分:3)
对“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()));
}
希望它有所帮助!
答案 6 :(得分:3)
使用此代码进行基本身份验证。
URL url = new URL(path);
String userPass = "username:password";
String basicAuth = "Basic " + Base64.encodeToString(userPass.getBytes(), Base64.DEFAULT);//or
//String basicAuth = "Basic " + new String(Base64.encode(userPass.getBytes(), Base64.No_WRAP));
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Authorization", basicAuth);
urlConnection.connect();
答案 7 :(得分:2)
我想为您无法控制打开连接的代码提供答案。就像我使用URLClassLoader
从受密码保护的服务器加载jar文件时所做的那样。
Authenticator
解决方案可行,但其缺点是它首先尝试在没有密码的情况下到达服务器,并且只有在服务器要求输入密码后才能提供密码。如果你已经知道服务器需要密码,这是一次不必要的往返。
public class MyStreamHandlerFactory implements URLStreamHandlerFactory {
private final ServerInfo serverInfo;
public MyStreamHandlerFactory(ServerInfo serverInfo) {
this.serverInfo = serverInfo;
}
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
switch (protocol) {
case "my":
return new MyStreamHandler(serverInfo);
default:
return null;
}
}
}
public class MyStreamHandler extends URLStreamHandler {
private final String encodedCredentials;
public MyStreamHandler(ServerInfo serverInfo) {
String strCredentials = serverInfo.getUsername() + ":" + serverInfo.getPassword();
this.encodedCredentials = Base64.getEncoder().encodeToString(strCredentials.getBytes());
}
@Override
protected URLConnection openConnection(URL url) throws IOException {
String authority = url.getAuthority();
String protocol = "http";
URL directUrl = new URL(protocol, url.getHost(), url.getPort(), url.getFile());
HttpURLConnection connection = (HttpURLConnection) directUrl.openConnection();
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
return connection;
}
}
这会注册一个新协议my
,在添加凭据时会被http
替换。因此,在创建新的URLClassLoader
时,只需将http
替换为my
,一切都很好。我知道URLClassLoader
提供了一个带URLStreamHandlerFactory
的构造函数,但如果URL指向jar文件,则不使用此工厂。
答案 8 :(得分:1)
从Java 9开始,您就可以这样做
URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setAuthenticator(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("USER", "PASS".toCharArray());
}
});
答案 9 :(得分:0)
ANDROD实施 从Web服务请求数据/字符串响应的完整方法,请求使用用户名和密码进行授权
public static String getData(String uri, String userName, String userPassword) {
BufferedReader reader = null;
byte[] loginBytes = (userName + ":" + userPassword).getBytes();
StringBuilder loginBuilder = new StringBuilder()
.append("Basic ")
.append(Base64.encodeToString(loginBytes, Base64.DEFAULT));
try {
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("Authorization", loginBuilder.toString());
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine())!= null){
sb.append(line);
sb.append("\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (null != reader){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
答案 10 :(得分:0)
我这样做你需要这样做只需复制粘贴就快乐
http://localhost:4200/admin/dashboard
答案 11 :(得分:0)
能够使用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);
从这篇文章中获取的更改很少。而Base64来自java.util包。