Java 尝试连接到URL以读取xml时出错401

Java 尝试连接到URL以读取xml时出错401,java,servlets,https,connection,inputstream,Java,Servlets,Https,Connection,Inputstream,我试图通过连接到url读取xml文件并读取输入流,但我有一个错误 “java.io.IOException:服务器为URL返回了HTTP响应代码:401:https://...." 我通过Authenticator类处理了身份验证的情况 代码如下: private static InputStream getConnection(String url) { InputStream in = null; try { final St

我试图通过连接到url读取xml文件并读取输入流,但我有一个错误 “java.io.IOException:服务器为URL返回了HTTP响应代码:401:https://...."

我通过Authenticator类处理了身份验证的情况

代码如下:

    private static InputStream getConnection(String url) {
        InputStream in = null;
        try {

            final String login="cloudtest@arrow.com";
            final String password="password";

            Authenticator.setDefault(new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {          
                    return new PasswordAuthentication(login, password.toCharArray());

                }
            });

             URL myUrl = new URL(url);


             URLConnection urlConn = myUrl.openConnection();
             urlConn.connect();
             in = urlConn.getInputStream();




        } catch (Exception e) {
            e.printStackTrace();
        }
        return in;
    } 
试试下面的代码

试试下面的代码


如何使用
验证器
将凭据传递给服务器?不确定是否已检查服务器支持的身份验证类型(基本/表单等)。如何使用
身份验证程序
将凭据传递给服务器?不确定是否已检查服务器支持的身份验证类型(基本/表单等)。同样的问题,错误401,我需要问一个问题。主机能否控制我如何连接URL并进行身份验证?是的,它在服务器上受控制。。。我的代码假定您的服务器正在使用基本身份验证。因此,在设置requestProperty时,我正在设置
Basic
,然后设置编码的用户名和密码谢谢rahul,我感谢您的回复,我会与他们沟通我也有同样的问题。不知何故,代码以前工作正常,但即使在很长一段时间内没有更改,它也只是停止工作,并出现“太多重定向”消息,该消息实际上是对同一验证器的多次调用,该验证器似乎无法访问资源,因此再次默认进行身份验证(同样的问题,错误401,我需要问一个问题。主机能否控制我如何连接URL并进行身份验证?是的,它在服务器上进行控制…我的代码假设您的服务器使用基本身份验证。因此,在设置requestProperty时,我设置了
basic
,然后设置了编码用户名和密码谢谢rahul,我感谢您的帮助。)回应,我会与他们沟通我也遇到了同样的问题。不知何故,代码以前工作正常,但即使在很长一段时间内没有被更改,它只是停止工作,并因“重定向太多”而失败消息,实际上是对同一身份验证程序的多次调用,该身份验证程序似乎无法访问资源,因此再次默认为进行身份验证:(
 private static InputStream getConnection(String url) {
    InputStream in = null;
    try {

        final String login="cloudtest@arrow.com";
        final String password="password";

        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {          
                return new PasswordAuthentication(login, password.toCharArray());

            }
        });

         URL myUrl = new URL(url);


         URLConnection urlConn = myUrl.openConnection();

         urlConn .setDoInput( true );

        // stuff the Authorization request header
        byte[] encodedPassword = ( login + ":" + password ).getBytes();
        BASE64Encoder encoder = new BASE64Encoder();
        urlConn .setRequestProperty( "Authorization",
                        "Basic " + encoder.encode( encodedPassword ) );


         urlConn.connect();
         in = urlConn.getInputStream();




    } catch (Exception e) {
        e.printStackTrace();
    }
    return in;
}