0

Can get from the response from Chrome, but when I want to get it with resttemplate it gives me 401 response.

I try to add the exact Content Types with rest template but it still gives the 401 error.

here is the request that i get it from 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

and here is the code that i used in java to connect the service :

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;
}
Saheb
  • 1,392
  • 3
  • 13
  • 33
mstfdz
  • 2,616
  • 3
  • 23
  • 27

1 Answers1

0

It appears to be a problem with encoding the authorization token generation. If you are sure about the username and password is correct, the only possibility is that the method/encoding used to generate the token is different on the browser(or the UI application which is generating the token) and the implementation of your createHeaders() method.

Please refer to the below links for more details:

What encoding should I use for HTTP Basic Authentication?

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

Hope it'll help.

Sandeep Kumar
  • 2,397
  • 5
  • 30
  • 37