【问题标题】:Error 401 while trying to connect to URL for reading xml尝试连接到 URL 以读取 xml 时出现错误 401
【发布时间】:2013-05-02 15:45:35
【问题描述】:

我正在尝试通过连接到 url 来读取 xml 文件并读取输入流,但是我遇到了错误 “java.io.IOException:服务器返回 HTTP 响应代码:401 for URL: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;
    } 

【问题讨论】:

  • 如何使用Authenticator 将凭据传递给服务器?不确定您是否检查了服务器支持的身份验证类型(基本/表单等)。

标签: java servlets https connection inputstream


【解决方案1】:

试试下面的代码Source

 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;
} 

【讨论】:

  • 同样的问题,错误401,我需要问一个问题。主机可以控制我如何连接 URL 并进行身份验证??
  • 是的,它在服务器上控制...我的代码假定您的服务器正在使用基本身份验证。所以在设置 requestProperty 我设置Basic 然后编码用户名和密码
  • 谢谢 rahul,感谢您的回复,我会与他们沟通
  • 我遇到了同样的问题。不知何故,代码以前可以正常工作,但即使很长时间没有更改,它也只是停止工作并且失败并显示“重定向过多”消息,这实际上是对同一身份验证器的多次调用,似乎无法访问资源,因此默认再次进行身份验证。 :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-07
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
相关资源
最近更新 更多