本文介绍了连接到需要使用Java进行身份验证的远程URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何连接到需要身份验证的Java远程URL。我试图找到一种方法来修改以下代码,以便能够以编程方式提供用户名/密码,因此它不会抛出401.
How do I connect to a remote URL in Java which requires authentication. I'm trying to find a way to modify the following code to be able to programatically provide a username/password so it doesn't throw a 401.
URL url = new URL(String.format("http://%s/manager/list", _host + ":8080"));
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
推荐答案
您可以为这样的http请求设置默认验证器:
You can set the default authenticator for http requests like this:
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});
此外,如果您需要更多灵活性,可以查看,它将为您提供更多身份验证选项(以及会话支持等)。
Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)
这篇关于连接到需要使用Java进行身份验证的远程URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!