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

时间:2013-05-08 12:04:00

标签: java servlets https connection inputstream

我试图通过连接到url来读取xml文件并读取输入流,但是我有一个错误 " java.io.IOException:服务器返回HTTP响应代码:401为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;
    } 

1 个答案:

答案 0 :(得分: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;
}