Java:使用 HTTPBasic 身份验证获取 URL

标签 java http authentication url http-authentication

我正在做一些简单的 HTTP 身份验证并得到一个

java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic OGU0ZTc5ODBk(...trimmed from 76 chars...)
(...more password data...)

我认为这是因为我有一个非常长的用户名和密码,并且编码器用 76 个字符的 \n 将其包装起来。有什么办法可以解决这个问题吗?该 URL 仅支持 HTTP 基本身份验证。

这是我的代码:

private class UserPassAuthenticator extends Authenticator {
    String user;
    String pass;
    public UserPassAuthenticator(String user, String pass) {
        this.user = user;
        this.pass = pass;
    }

    // This method is called when a password-protected URL is accessed
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, pass.toCharArray());
    }
}

private String fetch(StoreAccount account, String path) throws IOException {
    Authenticator.setDefault(new UserPassAuthenticator(account.getCredentials().getLogin(), account.getCredentials().getPassword()));

    URL url = new URL("https", account.getStoreUrl().replace("http://", ""), path);
    System.out.println(url);

    URLConnection urlConn = url.openConnection();
    Object o = urlConn.getContent();
    if (!(o instanceof String)) 
        throw new IOException("Wrong Content-Type on " + url.toString());

    // Remove the authenticator back to the default
    Authenticator.setDefault(null);
    return (String) o;
}

最佳答案

这似乎是一个 bug in Java .

您是否尝试过使用其他 HTTP 客户端,例如来自 Apache 的库?

或者不使用 Authenticator,而是手动设置 header ?

URL url = new URL("http://www.example.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic OGU0ZTc5ODBkABcde....");

token 值为 encodeBase64("username:password")。

关于Java:使用 HTTPBasic 身份验证获取 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2054687/

相关文章:

java - 更改 NoSuchBeanDefinitionException 上的 Spring 行为

java - 在静态父方法中访问子类常量

html - 这个套接字错误是什么意思?

java - 即使密码和确认密码匹配,也会出现 Toast 消息

rest - ASP.NET Web API 授权和身份验证

java - 打印最后出现的位置(打印错误)

java - Android - 将按钮与编辑 View 对齐稍微关闭

iOS-无法获取预期的 json 结果

javascript - JSFiddle "Blocked loading mixed active content"

php - 登录提交 php 不工作