Search code examples
javaspringapirestmicroservices

How to convert a RestTemplate to String when communicate between micro services in Java


I'm trying to communicate between two micro services here. I want to read the message written in one micro service from another micro service. I have used a RestTemplate for that. But When I tried to convert it to a String it won't coming. I'm getting this 'The method exchange(String, HttpMethod, HttpEntity<?>, Class, Object...) in the type RestTemplate is not applicable for the arguments (String, String, null, Class)'

@RequestMapping("/")
public String test(){
String a = restTemplate.exchange("http://localhost:8081/KDSystem/Testpro/pros", HttpMethod.GET,null,String.class).getBody().toString();
return a;
    }

Any idea of how to do that would be appreciated.


Solution

  • I'd suggest you to use getForObject(URI url, Class<T> responseType) method:

    @RequestMapping("/")
    public String test(){
      return restTemplate.getForObject("http://localhost:8081/KDSystem/Testpro/pros", String.class);
    }
    

    About the method exchange(String, HttpMethod, HttpEntity<?>, Class, Object...) according to exception text: you are trying to pass '(String, String, null, Class)' but the second argument should be HttpMethod.