【问题标题】:IOException in Basic Authentication for HTTP urlHTTP url 的基本身份验证中的 IOException
【发布时间】:2020-03-03 18:14:02
【问题描述】:

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

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点击相同的url,那么它会返回响应。下面是 curl 命令。

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

请帮我解决这个问题。

【问题讨论】:

    标签: java basic-authentication


    【解决方案1】:

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

    既然你说带有基本身份验证的 curl 命令正在工作,我会假设问题出在你的代码中。

    您似乎尝试关注this code.

    我能看到的唯一错误(但我无法确定这一点)是您只是将byte[] 转换为String,而不是使用Base64 对其进行编码。

    所以你应该改变这个:

    String authStringEnc = new String(authEncBytes);

    到此:

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

    另外,你想改变 这个:

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

    到此:

    byte[] authEncBytes = authString.getBytes();

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

    【讨论】:

    • 我在 StandardCharsets.UTF_8 上遇到错误。我导入了 java.io.IOException 但 UTF_8 出错
    • 在这种情况下,您可以只获取字符串的字节而不指定字符集。请参阅我的更新答案。
    猜你喜欢
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多