Home > Software design >  RestTemplate: While calling an API from one localhost to another i get error
RestTemplate: While calling an API from one localhost to another i get error

Time:07-02

I am working on spring boot project. In my eclipse I run two project first one is flight_system and second one is travel-site. I am sending request from travel-site to flight_system for get booking but i am getting error in postman. Url for get booking in flight_system is localhost:8050/booking which is work correctly in postman. Url for get booking in travel-site is localhost:8051/travel-site/booking which produce error in postman.

Here down is my code of flight_system:

Entity

@Entity
public class Booking {

    @Id
    private String bookingId;
    private String passangerName;
    private String flightName;
    private String source;
    private String destination;

    // getter setter constructor
}

Controller

@RestController
public class BookingController {

    @Autowired
    private BookingService bookingService;

    @GetMapping("/booking")
    public List<Booking> getBooking() {
        return bookingService.getAllBooking();
    }
}

Here down is my code of travel-site:

Model

public class Booking {

    private String bookingId;
    private String passangerName;
    private String flightName;
    private String source;
    private String destination;

    // getter setter constructor
}

Controller

@RestController
public class TravelSiteController {

    @Autowired
    private RestTemplate restTemplate;

    static final String baseUrl = "http://localhost:8050/";

    @GetMapping(value = "/travel-site/booking")
    public Booking getBooking() {

        ResponseEntity<Booking> responseEntity = restTemplate.exchange(baseUrl   "booking", HttpMethod.GET, null,
                Booking.class);
        return responseEntity.getBody();
    }
}

Stack trace in postman

"message": "Error while extracting response for type [class com.travelsite.model.Booking] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type com.travelsite.model.Booking from Array value (token JsonToken.START_ARRAY); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type com.travelsite.model.Booking from Array value (token JsonToken.START_ARRAY)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]"

CodePudding user response:

Try changing

 ResponseEntity<Booking> responseEntity = restTemplate.exchange(baseUrl   "booking", HttpMethod.GET, null,
                Booking.class);
        return responseEntity.getBody();

to

List<Booking> booking = restTemplate
  .getForObject(baseUrl   "booking",List.class);

To know better about rest template method you can go through this link

  • Related