Home > Mobile >  How to fetch data from http response entity?
How to fetch data from http response entity?

Time:06-27

I am using SpringBoot to fetch access Token from my client. I could not separate the Access Token from the responseEntity. Is there a way to Fetch the AccessToken data alone?

Here is the code:

public ResponseEntity generate_Access_token() {

    String url = "https://zoom.us/oauth/token";
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    final Gson gson = new Gson();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
    map.add("grant_type", "account_credentials");
    map.add("client_id", "XXX");
    map.add("client_secret", "XXX");
    map.add("account_id", "XXX");

    

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

    ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
    
    //ResponseEntity<String> response_data=new ResponseEntity<String>(response.toString(), HttpStatus.CREATED);     
    ResponseEntity<AccessTokenResponse> response_data = restTemplate.postForEntity( url, request , AccessTokenResponse.class );

    
    return response_data.getAccessToken();
    

    
    
    
    
}
class AccessTokenResponse{
      @JsonProperty("access_token")
      String accessToken;
      //other props you are interested in
      //  getters/setters

    public String getAccessToken() {
        return accessToken;
    }

    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }

} }

The response:

{
    "access_token": "eyJhbGciOiJIUzUxMiIsInYiOiIyLjAiLCJraWQiOiJlNDI1NDFkYi0zMTllLTRiMGYtOWIwMC04YTVlZmY4NTI2NTAifQ.eyJ2ZXIiOjcsImF1aWQiOiJjNWFjZThhNGRiNDY0NTJhM2YxNGNkZjcyZjY1MjU2NSIsImNvZGUiOiIxYldicXNVNVR3V1hDUEY5M2ZTbjdBR21xT1NKOXBUS0kiLCJpc3MiOiJ6bTpjaWQ6NjFtN2ppSXFUM2VMWDRuS0xZVUdGZyIsImdubyI6MCwidHlwZSI6MywiYXVkIjoiaHR0cHM6Ly9vYXV0aC56b29tLnVzIiwidWlkIjoianYwWWZyUDlRLWFLTlctTFVlSXRDZyIsIm5iZiI6MTY1NjMxNzM2MiwiZXhwIjoxNjU2MzIwOTYyLCJpYXQiOjE2NTYzMTczNjIsImFpZCI6IkJ4MnVOWHpHUWwtSHVDN3BITWF2NWciLCJqdGkiOiJlYTYwMDkwYS0wMWY1LTQwODctODgxMi0wNmQ2Mzk1NTI2ZGUifQ.nKiYXxCDbhQRsyR2pTu0nwegQKBHsSR9JT7CBnad5pPfBi4pVBISjGp6icRv2Nyv_L7lNzVBK8clW7Z5zM9TUg",
    "token_type": "bearer",
    "expires_in": 3599,
    "scope": "meeting:read:admin user:master user:read:admin user:write:admin"
}

CodePudding user response:

Make your life easier, not harder - use plain DTO

class AccessTokenResponse{
  @JsonProperty("access_token");
  String accessToken
  //other props you are interested in
  //  getters/setters
}

and then

   AccessTokenResponse response = restTemplate.postForObject( url, request , AccessTokenResponse.class );
    
   response.getAccessToken(); //here you have it
  • Related