Home > Enterprise >  How to GET data using RestTemplate exchange?
How to GET data using RestTemplate exchange?

Time:09-26

I'm currently sending a GET request which is returning a null body in the response.

@Service
public class CarService {
private RestTemplate restTemplate;
private final String url = "url";
private final String accessToken = "x";

@Autowired
public CarService () throws URISyntaxException {
    restTemplate = new RestTemplate();
}

public void fetchCars() throws URISyntaxException {
    HttpHeaders headers = new HttpHeaders();
    headers.setBearerAuth(accessToken);
    headers.setAccept(List.of(MediaType.APPLICATION_JSON));
    ResponseEntity<CarList> carList = restTemplate.exchange
            (RequestEntity.get(new URI(url)).headers(headers).build(), CarList.class);
}

}

The CarList.class looks like this:

@JsonIgnoreProperties(ignoreUnknown = true)
public class CarList{
    private List<Car> carList;

    public CarList(List<Car> carList) {
        this.carList= carList;
    }

    public CarList() {
    }

    public List<Car> getCarList() {
        return carList;
    }

    @Override
    public String toString() {
        return "CarList{"  
                "carList="   carList  
                '}';
    }
}

The response in Postman looks like this:

{
    "cars": [
        {
            "carUid": "aaaa-ccc-dd-cc-ee",
            "model": "hyundai",
            "price": 20000,
            "soldAt": "2021-09-24T22:10:15.307Z"
        }
    ]
}

Am I missing something? It's the first time I try to consume from a client, so take in consideration the most basic things that I might be missing.

I've already tested the GET request in Postman with the given accessToken and it's working fine.

CodePudding user response:

You carList object is private, try providing a setter method for this object and if the contract is fine, the deserialization will work fine.

@JsonIgnoreProperties(ignoreUnknown = true)
public class CarList{
    private List<Car> carList;

    public CarList(List<Car> carList) {
        this.carList= carList;
    }

    public CarList() {
    }

    public List<Car> getCarList() {
        return carList;
    }

    public setCarList(List<Car> carList) {
        this.carList= carList;
    }

    @Override
    public String toString() {
        return "CarList{"  
                "carList="   carList  
                '}';
    }
}
  • Related