Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"401 Unauthorized: [no body]" error using RestTemplate for POST operation

I am currently facing this error when i try send an API request to a URL using RestTemplate. I have previously used this same method to get the bearer token from a similar API url (i.e. https://sometesturl.com/v1/gettoken), although that operation was GET, while this one is POST. I've searched up a few posts and most of them suggested it had to do with the authorisation field in HttpHeaders, as a result I've tried to add/remove a string "Bearer " but no luck.

Here's the log:

org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized: [no body]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:105) ~[spring-web-5.3.4.jar:5.3.4]

Tried debugging and nothing seems out of order in the debugging tool.. enter image description here

Following is the relevant code segment, any help is appreciated:

        //Prepare request header
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", (bearerToken));
        //for above, I have also tried headers.add("Authorization", ("Bearer "+bearerToken));

        headers.add("accept", "application/json");
        headers.add("content-type", "application/json");
        MediaType mediaType = MediaType.APPLICATION_JSON;
        headers.setContentType(mediaType);

        //Prepare request body
        HttpEntity<String> entity = new HttpEntity<>("{\"test\":\"test\"}", headers);

        //Build API url
        String url = "https://sometesturl.com/v1/search";
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
        Integer timeoutConnectToken = Integer.valueOf("0");

        //Send request to essDocs api
         RestTemplate restTemplate = getRestTemplate(timeoutConnectToken);
         ResponseEntity<String> response = null;
         try {
                 response = restTemplate.exchange(uriBuilder.build().toUriString(), HttpMethod.POST, entity, String.class);
logger.info("Received Search API Response : {}", response);
             }    catch (ResourceAccessException e) {
                 logger.error("ResourceAccessException: {}", e.getMessage());
             }    catch (Exception e) {
                 logger.error("Error querying REST API: {}, {}", e.getMessage(), e);
             }
like image 692
Cheryl Avatar asked Nov 28 '25 19:11

Cheryl


1 Answers

Okay, I managed to resolve it. Instead of setting the Bearer token like this

headers.add("Authorization", (bearerToken));
//or another way i tried was headers.add("Authorization", ("Bearer "+bearerToken));

I have set it like this:

headers.setBearerAuth(bearerToken);

Documentation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBearerAuth(java.lang.String)

No idea why the first method doesn't work since pretty much almost every post i googled recommended that, but if the second method works then it works lol.

like image 58
Cheryl Avatar answered Nov 30 '25 07:11

Cheryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!