【问题标题】:How to send POST request to relative URL with RestTemplate?如何使用 RestTemplate 将 POST 请求发送到相对 URL?
【发布时间】:2017-04-16 03:20:28
【问题描述】:

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

【问题讨论】:

    标签: java spring spring-boot spring-mvc spring-restcontroller


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我很好奇,你为什么要从服务器内部向服务器发出请求?通常,控制器将由服务支持,那么为什么不直接调用此服务呢?
      • spring 具有热重载application.properties 值的功能。这可以通过在包含@Value 属性的类上使用@RefreshScope 来实现。不幸的是,spring需要POST请求<app-path>/refresh。 Und 不支持对该 url 的简单 GET 浏览器请求。所以我提供了一个简单的 GET 并在内部发送 POST。
      • 啊,那么我会将您的解决方案限定为黑客;)请参阅下面的答案
      • 我接受我的回答,因为最初的问题是关于如何发送相关的 POST 请求。无论如何,对于我的根本问题,正确的解决方案是使用RefreshEndpoint.refresh()。
      【解决方案3】:

      如果你想刷新 application.properties,你应该将 RefreshScope 自动连接到你的控制器中,并显式调用它,这样可以更容易地看到它发生了什么。 Here is an example

      @Autowired
      public RefreshScope refreshScope;
      
      refreshScope.refreshAll();
      

      【讨论】:

      • 注入RefreshEndpoint 并调用.refresh() 可能会更好,因为这正是POST 请求所做的。
      猜你喜欢
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 2018-10-29
      • 1970-01-01
      • 2020-09-04
      • 2011-05-06
      • 1970-01-01
      相关资源
      最近更新 更多