'I keep getting 401 [No Body response] using RestTemplateBuilder

I have two RestTemplate Beans, however sometimes when authRestTemplate is used get a 401 error (org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]) I'm not sure why this is happening since it does not happen consistently.

This is how I have configured my RestTemplate.

@Configuration
@RequiredArgsConstructor
public class AppConfig {

    private final FooConfig fooConfig;

    @Bean
    @LoadBalanced
    public RestTemplate authRestTemplate(final RestTemplateBuilder restTemplateBuilder){
        return restTemplateBuilder
                .basicAuthentication(fooConfig.getUsername(), fooConfig.getPassword())
                .build();
    }

    @Bean
    @LoadBalanced
    public RestTemplate basicRestTemplate(final RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder
                .build();
    }

}

If I am using the authRestTemplate it would look something like this

@Service
@RequiredArgsConstructor
public class authSubmissionServiceImpl implements CompletedApplicationService {
    private final RestTemplate authRestTemplate;
    private final FooConfig fooConfig;

    @Override
    public void doSomething() {
        try {
            
             Objects.requireNonNull(
                 authRestTemplate.getForObject(
                     String.format(somePath, fooConfig.getBaseUrl()),
                     String.class)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

I use constructor injection and use the same variable name as the RestTemplkete bean to differentiate between the two. Because of this, I don't need to use @Qualifier(). However, I know the authentication is being sent because 99% of the time the request goes through fine but there are spontaneous times where I get 401 [No Body] and I'm stumped. Any help would be greatly appreciated



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source