HTTP URL的基本身份验证中的IOException

问题描述 投票:1回答:1

我正在使用JAVA代码使用用户名:密码来访问HTTP网址。下面是我的代码

public static main (String args[]){
try{ 

                    String webPage = "http://00.00.000.000:8080/rsgateway/data/v3/user/start/";
        String name = "abc001";
        String password = "abc100";
        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        URL url = new URL(webPage);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setUseCaches(true);
            connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization","Basic " +authStringEnc);
                    connection.setRequestProperty("Accept", "application/xml");
                    connection.setRequestProperty("Content-Type", "application/xml");
        InputStream is = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();

        System.out.println("*** BEGIN ***");
        System.out.println(result);
        System.out.println("*** END ***");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

但是我收到401错误

java.io.IOException:服务器返回的HTTP响应代码:URL的401:

相同的网址,如果我使用curl命中,则返回响应。下面是curl命令。

curl -u abc001:abc100 http://00.00.000.000:8080/rsgateway/data/v3/user/start/

请帮助我解决这个问题。

java basic-authentication
1个回答
0
投票

您得到的代码是HTTP 401 Unauthorized,这意味着服务器未正确解释您的基本身份验证。

由于您说的是您显示的基本身份验证的curl命令正在运行,所以我认为问题出在您的代码中。

似乎您试图遵循this code.

我可以看到的唯一错误(但我无法确定是否能够进行测试,是您只是将byte[]强制转换为String而不是使用Base64对其进行编码。

所以您应该更改this:

String authStringEnc = new String(authEncBytes);

至此:] >>

String authStringEnc = Base64.getEncoder().encodeToString(authEncBytes);

此外,您想更改[this:

byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());

至此:

] >>

byte[] authEncBytes = authString.getBytes();

byte[] authEncBytes = authString.getBytes(StandardCharsets.UTF_8);

© www.soinside.com 2019 - 2024. All rights reserved.