如何使用 RestTemplate 向亲属 URL 发送 POST 请求?

How to send POST request to relative URL with RestTemplate?

如何向应用程序本身发送 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?我必须动态找到路径。

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

@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 自动连接到你的控制器中,并显式调用它,这样可以更容易地看到它发生了什么。

@Autowired
public RefreshScope refreshScope;

refreshScope.refreshAll();