membersound
membersound

Reputation: 86845

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.

Upvotes: 5

Views: 10217

Answers (3)

Klaus Groenbaek
Klaus Groenbaek

Reputation: 5045

If you want to refresh application.properties, you should AutoWire the RefreshScope into you controller, and call it explicitly, it make it much easier to see what it going on. Here is an example

@Autowired
public RefreshScope refreshScope;

refreshScope.refreshAll();

Upvotes: 1

membersound
membersound

Reputation: 86845

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);
    }

Upvotes: 7

abaghel
abaghel

Reputation: 15307

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);
}

Upvotes: 9

Related Questions