RestTemplate中post请求实用分析

1、最近在做相关平台对接工作。对接第一步需要在后端完成认证,拿到对方平台的access_token。由于对方文档不是很详细,根据认证需要的参数进行了多种尝试。顺带学习一下RestTemplate发post的请求的各种姿势。记录在此,以便查看。

2、往后端发post请求一般分为两种,
一种是普通的表单提交(Content-Type: application/x-www-form-urlencoded)。
另一种是JSON提交(Content-Type: application/json)。
当然后台接收的方式也不同,
普通表单提交从request.getParameter()就能获取。
JSON提交的的数据在io流中,可以通过request.getInputStream()获取。spring为我们提供了@RequestBody注解,简单易用。

3、了解上述内容之后,下面进行试验
①模拟表单提交(要知道,post请求也可以使用url传参奥)

/*** 1、使用uri传参形式,把参数拼接到url后面,并在占位符里给每个参数赋值一定意义的名字。然后把参数封装到 * Map中。 占位符中的参数名会去对应Map中的key找到参数的值以完成替换。* 传参并携带请求头*/@GetMapping("/auth1")public void auth1() {try {Map uriVariables = new LinkedHashMap(4);uriVariables.put("username", "name");uriVariables.put("password", "1234");uriVariables.put("type", "client");uriVariables.put("grant_type", "password");HttpHeaders headers = new HttpHeaders();headers.add("Authorization", "Basic aW90OmlvdA==");HttpEntity httpEntity = new HttpEntity(null, headers);ResponseEntity<String> entity = restTemplate.postForEntity("http://192.168.1.111:8086/auth/server?username={username}&password={password}&type={type}&grant_type={grant_type}", httpEntity, String.class, uriVariables);if (entity.getStatusCode().is2xxSuccessful()) {System.out.println(entity.getBody());} else {log.error("认证失败:[{}]", entity);}} catch (Exception e) {log.error("认证异常:[{}]", e.getMessage());}}/*** 2、使用uri传参形式,把参数拼接到url后面,在占位符里写上参数的索引位置。然后把参数放在可变长变量中。* 实际参数会根据参数索引位置完成替换* 传参并携带请求头*/@GetMapping("/auth2")public void auth2() {try {final String username = "name";final String password = "1234";final String type = "client";final String grant_type = "password";HttpHeaders headers = new HttpHeaders();headers.add("Authorization", "Basic aW90OmlvdA==");HttpEntity httpEntity = new HttpEntity(null, headers);ResponseEntity<String> entity = restTemplate.postForEntity("http://192.168.1.111:8086/auth/server?username={0}&password={1}&type={2}&grant_type={3}", httpEntity, String.class, username, password, type, grant_type);if (entity.getStatusCode().is2xxSuccessful()) {System.out.println(entity.getBody());} else {log.error("认证失败:[{}]", entity);}} catch (Exception e) {log.error("认证异常:[{}]", e.getMessage());}}/*** 3、把参数封装到LinkedMultiValueMap中,使用HttpEntity一并封装表单数据和请求头* 传参并携带请求头*/@GetMapping("/auth3")public void auth3() {try {MultiValueMap body = new LinkedMultiValueMap(4);body.add("username", "name");body.add("password", "1234");body.add("type", "client");body.add("grant_type", "password");HttpHeaders headers = new HttpHeaders();headers.add("Authorization", "Basic aW90OmlvdA==");HttpEntity httpEntity = new HttpEntity(body, headers);ResponseEntity<String> entity = restTemplate.postForEntity("http://192.168.1.111:8086/auth/server", httpEntity, String.class);if (entity.getStatusCode().is2xxSuccessful()) {System.out.println(entity.getBody());} else {log.error("认证失败:[{}]", entity);}} catch (Exception e) {log.error("认证异常:[{}]", e.getMessage());}}/*** 4、把参数封装到LinkedMultiValueMap中,只发送表单数据可以不使用HttpEntity * 传参不携带请求头*/@GetMapping("/auth4")public void auth4() {try {MultiValueMap body = new LinkedMultiValueMap(4);body.add("username", "name");body.add("password", "1234");body.add("type", "client");body.add("grant_type", "password");ResponseEntity<String> entity = restTemplate.postForEntity("http://192.168.1.111:8086/auth/server", body, String.class);if (entity.getStatusCode().is2xxSuccessful()) {System.out.println(entity.getBody());} else {log.error("认证失败:[{}]", entity);}} catch (Exception e) {log.error("认证异常:[{}]", e.getMessage());}}

②JSON提交的形式

  /*** 5、数据可以用map封装、可以用实体类封装、也可以是json格式的字符串*    携带请求头*/@GetMapping("/auth5")public void auth5() {try {Map body = new LinkedHashMap(4);body.put("username", "name");body.put("password", "1234");body.put("type", "client");body.put("grant_type", "password");HttpHeaders headers = new HttpHeaders();headers.add("Authorization", "Basic aW90OmlvdA==");HttpEntity httpEntity = new HttpEntity(body, headers);ResponseEntity<String> entity = restTemplate.postForEntity("http://192.168.1.111:8086/auth/server2", httpEntity, String.class);if (entity.getStatusCode().is2xxSuccessful()) {System.out.println(entity.getBody());} else {log.error("认证失败:[{}]", entity);}} catch (Exception e) {log.error("认证异常:[{}]", e.getMessage());}}/*** 5、数据可以用map封装、可以用实体类封装、也可以是json格式的字符串*    不携带请求头*/@GetMapping("/auth6")public void auth6() {try {Map body = new LinkedHashMap(4);body.put("username", "name");body.put("password", "1234");body.put("type", "client");body.put("grant_type", "password");ResponseEntity<String> entity = restTemplate.postForEntity("http://192.168.1.111:8086/auth/server2", body, String.class);if (entity.getStatusCode().is2xxSuccessful()) {System.out.println(entity.getBody());} else {log.error("认证失败:[{}]", entity);}} catch (Exception e) {log.error("认证异常:[{}]", e.getMessage());}}

4、附上后台接收代码

    @PostMapping("/server")public String server(String username, String password, String type, String grant_type, HttpServletRequest request) {System.out.println(username);System.out.println(password);System.out.println(type);System.out.println(grant_type);String header = request.getHeader("Authorization");System.out.println(header);return "ok";}@PostMapping("/server2")public String server(@RequestBody Object obj, HttpServletRequest request) {System.out.println(obj);String header = request.getHeader("Authorization");System.out.println(header);return "ok";}

5、最后附上抓包数据,可以清楚的观察到数据的传送格式以及Content-Type的形式

POST /auth/server?username=name&password=1234&type=client&grant_type=password HTTP/1.1
Accept: text/plain, application/json, application/*+json, */*
Authorization: Basic aW90OmlvdA==
Content-Length: 0
Host: 192.168.1.111:8086
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.8 (Java/1.8.0_131)
Accept-Encoding: gzip,deflatePOST /auth/server?username=name&password=1234&type=client&grant_type=password HTTP/1.1
Accept: text/plain, application/json, application/*+json, */*
Authorization: Basic aW90OmlvdA==
Content-Length: 0
Host: 192.168.1.111:8086
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.8 (Java/1.8.0_131)
Accept-Encoding: gzip,deflatePOST /auth/server HTTP/1.1
Accept: text/plain, application/json, application/*+json, */*
Authorization: Basic aW90OmlvdA==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 59
Host: 192.168.1.111:8086
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.8 (Java/1.8.0_131)
Accept-Encoding: gzip,deflateusername=name&password=1234&type=client&grant_type=passwordPOST /auth/server HTTP/1.1
Accept: text/plain, application/json, application/*+json, */*
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 59
Host: 192.168.1.111:8086
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.8 (Java/1.8.0_131)
Accept-Encoding: gzip,deflateusername=name&password=1234&type=client&grant_type=passwordPOST /auth/server2 HTTP/1.1
Accept: text/plain, application/json, application/*+json, */*
Authorization: Basic aW90OmlvdA==
Content-Type: application/json;charset=UTF-8
Content-Length: 77
Host: 192.168.1.111:8086
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.8 (Java/1.8.0_131)
Accept-Encoding: gzip,deflate{"username":"name","password":"1234","type":"client","grant_type":"password"}POST /auth/server2 HTTP/1.1
Accept: text/plain, application/json, application/*+json, */*
Content-Type: application/json;charset=UTF-8
Content-Length: 77
Host: 192.168.1.111:8086
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.8 (Java/1.8.0_131)
Accept-Encoding: gzip,deflate{"username":"name","password":"1234","type":"client","grant_type":"password"}

6、总结:
在做平台对接的时候,一开始使用的是第三种形式发送post请求。经过一番调试,没有认证成功。但是我通过postman请求是成功的。通过抓包,发现postman发送数据的形式是前面两种形式,即把参数放在url上。后来在程序中切换到前两种形式,成功认证并获取到对方平台的accessToken。由于不知道对方代码的实现方式,故无法进一步分析。
在我的试验中以前三种形式进行表单提交都能正常获取到数据,若今后遇到类似问题,要做到举一反三、触类旁通。

7、小尾巴~~
只要有积累,就会有进步

RestTemplate中post请求实用分析相关推荐

  1. unity3d中画线有几种方式_Spring RestTemplate中几种常见的请求方式

    原文 https://segmentfault.com/a/1190000011093597 在Spring Cloud中服务的发现与消费一文中,当我们从服务消费端去调用服务提供者的服务的时候,使用了 ...

  2. Spring RestTemplate中几种常见的请求方式

    关注公众号[江南一点雨],专注于 Spring Boot+微服务以及前后端分离等全栈技术,定期视频教程分享,关注后回复 Java ,领取松哥为你精心准备的 Java 干货! 在Spring Cloud ...

  3. Spring RestTemplate中几种常见的请求方式GET请求 POST请求 PUT请求 DELETE请求

    Spring RestTemplate中几种常见的请求方式 原文地址: https://blog.csdn.net/u012702547/article/details/77917939 版权声明:本 ...

  4. Java RestTemplate中几种常见的请求方式

    在REST接口的设计中,利用RestTemplate进行接口测试是种常见的方法.本文主要从以下四个方面来看RestTemplate的使用: GET请求 POST请求 PUT请求 DELETE请求 OK ...

  5. Spring中使用RestTemplate发送Http请求

    作为一个Java开发选手,平时调用外部服务都是通过PRC接口,而这次业务下游只提供Http接口,就有点捉急... RestTemplate的基本使用 RestTemplate是spring实现的,基于 ...

  6. 拦截器获取请求参数post_「SpringBoot WEB 系列」RestTemplate 之自定义请求头

    [WEB 系列]RestTemplate 之自定义请求头 上一篇介绍了 RestTemplate 的基本使用姿势,在文末提出了一些扩展的高级使用姿势,本篇将主要集中在如何携带自定义的请求头,如设置 U ...

  7. 设置datalist 中option的宽度_Flutter中http请求抓包的完美解决方案

    前言 前阵子有同学反馈Flutter中的http请求无法通过fiddler抓包,作者喜欢使用Charles抓包工具,于是抽时间写了个小demo测试了一下,结论是在手机上设置代理,Charles确实抓不 ...

  8. LoadRunner中对图表的分析说明

    (一)在Vusers(虚拟用户状态)中 1.Running Vusers(负载过程中的虚拟用户运行情况) 说明--系统形成负载的过程,随着时间的推移,虚拟用户数量是如何变化的,描述为(用户在几分钟左右 ...

  9. HBase建表高级属性,hbase应用案例看行键设计,HBase和mapreduce结合,从Hbase中读取数据、分析,写入hdfs,从hdfs中读取数据写入Hbase,协处理器和二级索引

    1. Hbase高级应用 1.1建表高级属性 下面几个shell 命令在hbase操作中可以起到很到的作用,且主要体现在建表的过程中,看下面几个create 属性 1. BLOOMFILTER 默认是 ...

最新文章

  1. 《SQL Server 2012 T-SQL基础》读书笔记 - 1.背景
  2. python安装不了bs4_怎么在python安装bs4
  3. wordpress使用的插件记录
  4. java标识符遵循规范
  5. OpenCV距离变换和分水岭算法的图像分割
  6. nginx mac 服务器 html,Mac上搭建 nginx 服务器
  7. 雷军正式入驻B站,或为小米新品直播带货做准备
  8. java服务器向客户端发消息_socket 服务器向指定的客户端发消息
  9. OSPF特殊区域(末梢区域、NSSA) 路由优化
  10. 将dubbo暴露HTTP服务
  11. 如何将matlab设置为默认打开方式,如何设置默认打开方式
  12. java生成自己的Doc文档
  13. 我实测了国内外GPT,问了10个问题,差点把电脑砸了...
  14. 虚拟地址,虚拟地址空间, 交换分区
  15. 通过Mycat分库分表
  16. (二十七)论文阅读 | 目标检测之MAL
  17. java实现截取视频方法
  18. 初学者古琴入门知识——【唐畅古琴】
  19. C语言编译过程中*.i *.s *.o *.out 等文件是什么?
  20. html单选按钮样式 正方形,HTML自定义radio单选按钮(纯css版,样式可以随便改变)

热门文章

  1. Python3爬虫爬取房价进行房价预测-张敏-专题视频课程
  2. 中科院张家俊:ChatGPT中的提示与指令学习
  3. 东北大学CSDN俱乐部“Windows 8平台开发介绍会暨ImagineCup2013 微软“创新杯”全球学生大赛说明会”成功举办(2012年11月)
  4. 无线图传发射模块静电浪涌测试
  5. 网络对抗技术实验报告一
  6. java中replaceall用法_java中replaceall的用法
  7. Coding and Paper Letter(三十三)
  8. 以太坊ETH-智能合约开发-solidity源码分析-truffle进阶
  9. 【每日一题】打卡 11
  10. Excel数据分析工具查找和使用