如何使用RestTemplate发送POST请求到相对URL?

4
我该如何向应用程序本身发送POST请求?
如果我只发送相对的post请求: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);
    }
}

那么,使用上面的示例,我如何将URL前缀与绝对服务器URL路径localhost:8080/app结合使用?我必须动态地查找路径。

3个回答

8
你可以像下面这样重写你的方法。
@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);
}

6

我发现了一种很棒的方法,使用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);
    }

我很好奇,为什么你想从服务器内部向服务器发出请求?通常控制器会由服务支持,那么为什么不直接调用这个服务呢? - Klaus Groenbaek
Spring提供了一个功能,可以实现热重新加载application.properties的值。这可以通过在包含@Value属性的类上使用@RefreshScope来实现。不幸的是,Spring要求使用POST请求到<app-path>/refresh。它不支持在该URL上进行简单的GET浏览器请求。所以我提供了一个简单的GET请求并在内部发送POST请求。 - membersound
啊,那我会把你的解决方案归类为“hack”(非正式且不太好的解决方法);请看下面的回答。 - Klaus Groenbaek
我接受我的答案,因为最初的问题是关于如何发送相对POST请求的。无论如何,对于我的根本问题,正确的解决方案应该是使用RefreshEndpoint.refresh() - membersound

1
如果您想刷新application.properties文件,您应该在控制器中自动装配RefreshScope,并显式调用它,这将使其更容易看到正在发生的事情。 这里是一个例子
@Autowired
public RefreshScope refreshScope;

refreshScope.refreshAll();

最好的方法可能是注入RefreshEndpoint并调用.refresh(),因为这正是POST请求所做的。 - membersound

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接