4

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.

abaghel
  • 14,783
  • 2
  • 50
  • 66
membersound
  • 81,582
  • 193
  • 585
  • 1,120

3 Answers3

8

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);
}
abaghel
  • 14,783
  • 2
  • 50
  • 66
6

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);
    }
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • I'm curious, why would you want to make a request to a server from inside the server? Typically a controller will be backed by a service, so why don't you just call this service directly ? – Klaus Groenbaek Dec 01 '16 at 13:57
  • spring has a feature for hot reloading `application.properties` values. This can be achieved by using the `@RefreshScope` on classes that contain `@Value` properties. Unfortunately spring requires a `POST` request to `/refresh`. Und does not support simple `GET` browser request on that url. So I'm providing a simple GET and internally send the POST. – membersound Dec 01 '16 at 14:54
  • Ahh, then I would qualify you solution as a hack ;) see my answer below – Klaus Groenbaek Dec 01 '16 at 16:17
  • I'm accepting my anwer as the initial question was about how to send relative POST requests. Anysways for my root problem the correct solution would be using the `RefreshEndpoint.refresh()`. – membersound Dec 05 '16 at 10:38
1

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();
Community
  • 1
  • 1
Klaus Groenbaek
  • 4,820
  • 2
  • 15
  • 30
  • It might be even better to inject `RefreshEndpoint` and call `.refresh()`, as this is exactly what the POST request does. – membersound Dec 05 '16 at 10:33