连接到需要使用 Java 进行身份验证的远程 URL [英] Connecting to remote URL which requires authentication using Java

查看:32
本文介绍了连接到需要使用 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());
    }
});

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆