2016-12-01 66 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