2016-12-01 141 views
2

如何向应用程序本身发送POST请求?如何使用RestTemplate将POST请求发送到相对URL?

如果我只是发送一个相对帖子请求: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路径localhost:8080/app的网址是什么?我必须动态地找到路径。

回答

4

研究发现,基本上使用自动化的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); 
    } 
+0

我很好奇,为什么你会想从服务器内建立到服务器的请求?通常情况下,控制器将由服务提供支持,那么为什么不直接调用此服务? –

+0

spring有一个热重载'application.properties'值的功能。这可以通过在包含'@ Value'属性的类上使用'@ RefreshScope'来实现。不幸的是,spring需要'POST'请求​​'/refresh'。 Und不支持该网址上的简单GET请求。所以我提供了一个简单的GET并在内部发送POST。 – membersound

+0

呵呵,那么我会认为你的解决方案是黑客;)看到我的回答在 –

7

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

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

如果要刷新application.properties,你应该自动装配的RefreshScope到你的控制器,并明确调用它,它让它更容易看到它发生了什么。 Here is an example

@Autowired 
public RefreshScope refreshScope; 

refreshScope.refreshAll(); 
+0

注入'RefreshEndpoint'并调用'.refresh()'可能会更好,因为这正是POST请求的作用。 – membersound