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

Java 如何使用RestTemplate将POST请求发送到相对URL?,java,spring,spring-boot,spring-mvc,spring-restcontroller,Java,Spring,Spring Boot,Spring Mvc,Spring Restcontroller,如何向应用程序本身发送POST请求 如果我只是发送一个相对post请求:java.lang.IllegalArgumentException:URI不是绝对的 @RestController public class TestServlet { @RequestMapping("value = "/test", method = RequestMethod.GET) public void test() { String relativeUrl = "/posti

如何向应用程序本身发送
POST
请求

如果我只是发送一个相对post请求:
java.lang.IllegalArgumentException:URI不是绝对的

@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路径
localhost:8080/app
作为url前缀?我必须动态地找到路径。

您可以像下面这样重写您的方法

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

找到了一种使用
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);
    }

如果要刷新application.properties,应该将RefreshScope自动连接到控制器中,并显式调用它,这样可以更容易地查看它的运行情况。


我很好奇,为什么要从服务器内部向服务器发出请求?通常,一个控制器将由一个服务支持,所以为什么不直接调用这个服务呢?spring有一个热重新加载
application.properties
value的功能。这可以通过在包含
@Value
属性的类上使用
@RefreshScope
来实现。不幸的是,spring需要一个
POST
请求来
/refresh
。Und不支持该url上的简单
GET
浏览器请求。因此,我提供了一个简单的GET并在内部发送帖子。啊,那么我会将您的解决方案视为黑客;)我接受我的回答,因为最初的问题是关于如何发送相关的POST请求。对于我的根本问题,正确的解决方案是使用
RefreshEndpoint.refresh()
。注入
RefreshEndpoint
并调用
.refresh()
,因为这正是POST请求所做的。
@Autowired
public RefreshScope refreshScope;

refreshScope.refreshAll();