Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send POST request to relative URL with RestTemplate?

How can I send a POST request to the application itself?

If I just send a relative post request: java.lang.IllegalArgumentException: URI is not absolute.

@RestController
public class TestServlet {
    @RequestMapping("value = "/test", method = RequestMethod.GET)
    public void test() {
        String relativeUrl = "/posting"; //TODO how to generate like "localhost:8080/app/posting"?
        new RestTemplate().postForLocation(relativeUrl, null);
    }
}

So using the example above, how can I prefix the url with the absolute server url path localhost:8080/app? I have to find the path dynamically.

like image 671
membersound Avatar asked Dec 06 '22 16:12

membersound


2 Answers

You can rewrite your method like below.

@RequestMapping("value = "/test", method = RequestMethod.GET)
public void test(HttpServletRequest request) {
    String url = request.getRequestURL().toString();
    String relativeUrl = url+"/posting"; 
    new RestTemplate().postForLocation(relativeUrl, null);
}
like image 179
abaghel Avatar answered Jan 16 '23 02:01

abaghel


Found a neat way that basically automates the task using ServletUriComponentsBuilder:

@RequestMapping("value = "/test", method = RequestMethod.GET)
    public void test(HttpServletRequest req) {
    UriComponents url = ServletUriComponentsBuilder.fromServletMapping(req).path("/posting").build();
        new RestTemplate().postForLocation(url.toString(), null);
    }
like image 33
membersound Avatar answered Jan 16 '23 01:01

membersound