Problem:
Controller Code:
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class StudentController {
@GetMapping(value = "/getstudent")
private Student getStudent(HttpServletRequest request)
{
String uri = "/student";
RestTemplate restTemplate = new RestTemplate();
Student student= restTemplate.getForObject(uri, Student.class);
return student;
}
}
Every time I run my Java application I get below exception-
2022-02-23 17:15:08.417 ERROR 20534 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: URI is not absolute] with root cause
java.lang.IllegalArgumentException: URI is not absolute
at java.net.URI.toURL(URI.java:1088) ~[na:1.8.0_101]
at org.springframework.http.client.SimpleClientHttpRequestFactory.createRequest(SimpleClientHttpRequestFactory.java:145) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.http.client.support.HttpAccessor.createRequest(HttpAccessor.java:124) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:735) ~[spring-web-5.2.9.RELEASE.jar:5.2.9.RELEASE]
Solution
In above code, URL getting passed in restTemplate is not an absolute URL ("/student") due to which this error is happening. Instead you should be passing full URL like "http://localhost:8080/student".
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class StudentController {
@GetMapping(value = "/getstudent")
private Student getStudent(HttpServletRequest request)
{
String uri = "http://localhost:8080/student";
RestTemplate restTemplate = new RestTemplate();
Student student= restTemplate.getForObject(uri, Student.class);
return student;
}
}