mem*_*und 3 java spring spring-mvc spring-web spring-restcontroller
如何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);
}
}
Run Code Online (Sandbox Code Playgroud)
所以使用上面的例子,我如何在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);
}
Run Code Online (Sandbox Code Playgroud)
发现一种基本的方式,基本上使用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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6423 次 |
| 最近记录: |