Spring

Wesley13
• 阅读 432

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方法为例,创建以下服务:

    @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提供实现。

Spring

代码示例

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

    }

结果

返回字符串

{"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"}

返回对象

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

创建返回值对应的对象

public class UserVo {
    private String code;
    private String msg;
    private List<User> result;
    }

以对象的类型接受返回值

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

返回结果:

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是非线程安全的。

Spring

代码示例

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

结果

{"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

点赞
收藏
评论区
推荐文章
blmius blmius
1年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Easter79 Easter79
1年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
helloworld_34035044 helloworld_34035044
11个月前
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
1年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Stella981 Stella981
1年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
1年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
1年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
1年前
Android蓝牙连接汽车OBD设备
//设备连接public class BluetoothConnect implements Runnable {    private static final UUID CONNECT_UUID  UUID.fromString("0000110100001000800000805F9B34FB");
Stella981 Stella981
1年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
1年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_