Problem when making a POST request

Asked

Viewed 41 times

-2

Hi, I’m trying to make a POST type request with Bearer token for an endpoint. When I perform this request by the postamn it returns normally, but when it is performed by the method I created using java’s Resttemplate api, it gives the error "401 Unauthorized". Follow the code below:

public <T> T sendRequestWithBody(String urlRequest, String jsonValue){
        HttpHeaders header = new HttpHeaders();
        header.set("Autorization", "Bearer  ".concat(getToken()));

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("query", jsonValue);

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<?> request = new HttpEntity<>(jsonObject.toString(), header);

       ParameterizedTypeReference<T> typeRef = new ParameterizedTypeReference<T>() {
       };

       ResponseEntity<T> response = restTemplate.exchange(urlRequest, HttpMethod.POST, request, typeRef);

        return response.getBody();
    }

Could someone help? Note: I made a method very similar to this to pick up the token, and it generates normally

1 answer

0


If the mistake is 401 it has to do with your header.

Mount the request header (headers) this way:

String accessToken = "Bearer " + getToken();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization", accessToken);
headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());

The way you are mounting the json you are sending, it will look like this: {'query': 'valor na variavel json value'} That’s the whole point?

I usually use the method postForObject instead of exchange. I find it simpler.

Of documentation:

exchange

More Generalized (and Less Opinionated) version of the preceding methods that provides extra flexibility when needed. It accepts a Requestentity (including HTTP method, URL, headers, and body as input) and Returns a Responseentity.

These methods allow the use of Parameterizedtypereference Instead of Class to specify a Response type with Generics.

postForObject

Creates a new Resource by using POST and Returns the representation from the Sponse.

I’ll put a full example here using postForObject. I ran a test here and it’s working.

    @RequestMapping("/teste")
    @ResponseBody
    public String testeRestClient() {

        String accessToken = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZWxsZXJJZCI6Niwic2NvcGUiOlsibWFy"; 
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization", accessToken);
        headers.add("Content-Type", MediaType.APPLICATION_JSON.toString());

        String urlRequest = "http://localhost:8080/books";
        
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", "titulo 2");
        jsonObject.put("author", "fulano de tal");
        jsonObject.put("price", new BigDecimal(30));
        
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> entity = new HttpEntity<String>(jsonObject.toString(), headers);
        String result = restTemplate.postForObject(urlRequest, entity, String.class);
        return result;
    }
  • Hello. It worked that way!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.