Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

spring - Get specific response value from the API in SpringBoot

I am calling one post call and getting the response like below : enter image description here

Now I want to get the value of the access token and do some logic. How to get the value from the response? Can anyone please help. Service code of the API.

public String getToken(User user) throws JsonMappingException, JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(clientId+clientPass);
        String plainCreds = clientId+":"+clientPass;
        byte[] plainCredsBytes = plainCreds.getBytes();
        byte[] base64CredsBytes = Base64.getEncoder().encode(plainCredsBytes);
        String base64Creds = new String(base64CredsBytes);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64Creds);
        HttpEntity<String> request=new HttpEntity<String>(headers);
        String uri = url+ user.getUser_id()
                + "&password=" + user.getPassword();
        RestTemplate restTemplate = new RestTemplate();
        
        ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, request, String.class) ;
        JsonNode newNode = mapper.readTree(result.getBody());
        ObjectNode node = ((ObjectNode) newNode).put("Authentication", "Successful");
        
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can write DTO for response:

public class ResponseSample {
   @JsonProperty("access_token")
   String accessToken;
   ....
}

(or deserialize to Map) and instead calling ResponseEntity<String> result = restTemplate.exchange(...) you can call

ResponseEntity<ResponseSample> result = restTemplate.exchange(..., ResponseSample.class)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...