【问题标题】:Can get response from browser, but 401 unauthorized from resttemplate可以从浏览器获得响应,但 401 未授权来自 resttemplate
【发布时间】:2018-11-30 20:57:24
【问题描述】:

可以从 Chrome 的响应中获取,但是当我想使用 resttemplate 获取它时,它会给我 401 响应。

我尝试使用 rest 模板添加确切的内容类型,但它仍然给出 401 错误。

这是我从 Chrome 获得的请求:

GET URL HTTP/1.1
Host: host
Connection: keep-alive
Cache-Control: max-age=0
Authorization: Basic auth
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en,de;q=0.9,tr;q=0.8

这是我在 java 中用来连接服务的代码:

RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_XHTML_XML, MediaType.APPLICATION_XML, MediaType.TEXT_HTML));
messageConverters.add(converter);
restTemplate.setMessageConverters(messageConverters);
HttpEntity<Map<String, String>> entity = new HttpEntity<>(params,createHeaders(username, password));

restTemplate.getForObject("URL",String.class, entity);

public static HttpHeaders createHeaders(String username, String password) {
    String auth = username + ":" + password;
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
    String authHeader = "Basic " + new String(encodedAuth);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("Authorization", authHeader);
    return httpHeaders;
}

【问题讨论】:

    标签: java rest http https resttemplate


    【解决方案1】:

    这似乎是对授权令牌生成进行编码的问题。 如果您确定用户名和密码正确,唯一的可能是用于生成令牌的方法/编码在浏览器(或生成令牌的 UI 应用程序)和您的 createHeaders() 的实现上不同方法。

    更多详情请参考以下链接:

    What encoding should I use for HTTP Basic Authentication?

    https://github.com/request/request/issues/1334

    希望对你有所帮助。

    【讨论】:

    • 不,不是,检查了两个令牌,它们是相同的
    猜你喜欢
    • 1970-01-01
    • 2021-09-03
    • 2021-01-04
    • 2020-08-08
    • 1970-01-01
    • 2016-02-10
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多