The RestTemplate is the core class for client-side access to RESTful services. It is conceptually similar to other template classes in Spring, such as JdbcTemplate and JmsTemplate and other template classes found in other Spring portfolio projects.
前言
这里总结一下,怎么用代码发起HTTP请求:Post、Get等。之前类似的请求都是用Postman。RestTemplate网上教程也是很多,但是编程就是要多实战,可能受制于版本等各种客观因素,同样的教程实战可能会有不同的结果。
对于实现HTTP请求有多种类库,目前用过RestTemplate和HttpComponents,以Post方法为例,创建以下服务:
@RequestMapping(value = "/selectPost", method = RequestMethod.POST)
public ModelMap selectPost(String username, String password) {
List<User> userList = userService.selectPost(username, password);
return result(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, userList);
}
RestTemplate
RestTemplate支持以下6六种HTTP请求方法。这些请求方法是定义在RestOperations接口中的,RestTemplate提供实现。
代码示例
@Test
public void selectPost1() {
//参数
String url = "http://localhost:9091/user/selectPost";
String username = "admin";
String password = "1212";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("username", username);
map.add("password", password);
//设置响应头
HttpHeaders headers = new HttpHeaders();

最低0.47元/天 解锁文章
3356

被折叠的 条评论
为什么被折叠?



