前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring-RestTemplate实战

Spring-RestTemplate实战

作者头像
用户2146693
发布2019-08-08 11:43:37
8340
发布2019-08-08 11:43:37
举报
文章被收录于专栏:架构师进阶架构师进阶

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请求有多种类库,目前用过RestTemplateHttpComponents,以Post方法为例,创建以下服务:

代码语言:javascript
复制
    @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提供实现。

这里写图片描述
这里写图片描述

代码示例

代码语言:javascript
复制
    @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();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //封装参数响应头
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(map, headers);


        RestTemplate template = new RestTemplate();
        //执行请求,并接受返回结果
        ResponseEntity<String> result = template.exchange(url, HttpMethod.POST, entity, String.class);
        JSONObject jsonObject = JSONObject.fromString(result.getBody());
        System.out.println("===========selectPost1===============");

        System.out.println(jsonObject);

    }

结果

返回字符串
代码语言:javascript
复制
{"msg":"SUCCESS","result":[{"password":"1212","createTime":"2017-38-14 07:38:05","updateUser":"admin","createUser":"admin","updateTime":"2017-38-14 07:38:05","id":3,"username":"admin"},{"password":"1212","createTime":"2017-39-14 07:39:47","updateUser":"admin","createUser":"admin","updateTime":"2017-39-14 07:39:47","id":4,"username":"admin"}],"code":"200"}
返回对象

通常返回一个字符串在项目中用处不大,如果能够直接返回相应的实体,那就更好了。

创建返回值对应的对象

代码语言:javascript
复制
public class UserVo {
    private String code;
    private String msg;
    private List<User> result;
    }

以对象的类型接受返回值

UserVo result = template.postForObject(url, entity, UserVo.class);

返回结果:

代码语言:javascript
复制
UserVo{code='200', msg='SUCCESS', result=[User{id=3, username='admin', password='1212', createUser='admin', createTime=Sat Jan 14 15:38:05 CST 2017, updateUser='admin', updateTime=Sat Jan 14 15:38:05 CST 2017}, User{id=4, username='admin', password='1212', createUser='admin', createTime=Sat Jan 14 15:39:47 CST 2017, updateUser='admin', updateTime=Sat Jan 14 15:39:47 CST 2017}]}

HttpComponents

HttpComponents是Apache下的一个项目,目前最新的版本是4.5.3。 需要说明一下,4.3.6中提供的HttpPost是非线程安全的。

这里写图片描述
这里写图片描述

代码示例

代码语言:javascript
复制
    @Test
    public void selectPost3() {
        //参数
        String url = "http://localhost:9091/user/selectPost";
        String username = "admin";
        String password = "1212";

        try {
            //初始化
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse httpResponse = null;
            HttpPost httpPost = new HttpPost(url);

            //请求参数
            List<NameValuePair> nameValuePairs = new ArrayList<>();
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));

            //编码 封装参数
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs, "utf-8");
            httpPost.setEntity(formEntity);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

            //执行请求
            httpResponse = httpClient.execute(httpPost);

            //返回结果
            org.apache.http.HttpEntity respHttpEntity = httpResponse.getEntity();
            String resultStr = EntityUtils.toString(respHttpEntity, "utf-8");

            System.out.println(resultStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

结果

代码语言:javascript
复制
{"code":"200","msg":"SUCCESS","result":[{"id":3,"username":"admin","password":"1212","createUser":"admin","createTime":"2017-38-14 07:38:05","updateUser":"admin","updateTime":"2017-38-14 07:38:05"},{"id":4,"username":"admin","password":"1212","createUser":"admin","createTime":"2017-39-14 07:39:47","updateUser":"admin","updateTime":"2017-39-14 07:39:47"}]}

扩展

HttpComponents 结构

  • HttpComponents Core 是一组低级的HTTP传输组件,支持2中I/O模型:基于经典Java I/O的阻塞I/O和非阻塞I/O。
  • HttpComponents Client 是一个基于HttpCore的符合HTTP/1.1标准的HTTP代理实现。
  • HttpComponents AsyncClient 是一个基于HttpCore NIO的符合HTTP/1.1标准的HTTP代理实现和HttpClient组件。

参考

对于学习编程的态度一贯是多实战,实战才能发现问题。以上只是简单实现了一下,有些内容深入不够,后续还得继续深入了解。

Class RestTemplate 28.10 Accessing RESTful services on the Client Spring RestTemplate介绍 Apache HttpComponents

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • RestTemplate
    • 代码示例
      • 结果
        • 返回字符串
        • 返回对象
    • HttpComponents
      • 代码示例
        • 结果
          • 扩展
          • 参考
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档