嗷嗷待哺的controller(被调用provider的controller方法)

    //测试get少量参数
@RequestMapping(value = "detailsGetD",method = RequestMethod.GET)
public String test05(Integer id,String name){
System.out.println("GET-"+id+"-"+name);
return "error";
}
//测试post
@RequestMapping(value = "detailsPostD",method = RequestMethod.POST)
public String test06(Integer id,String name){
System.out.println("POST-"+id+"-"+name);
return "error";
}
//测试put
@RequestMapping(value = "detailsPutD",method = RequestMethod.PUT)
public String test07(Integer id,String name){
System.out.println("PUT-"+id+"-"+name);
return "error";
}
//测试delete
@RequestMapping(value = "detailsDeleteD",method = RequestMethod.DELETE)
public String test08(Integer id,String name){
System.out.println("DELETE-"+id+"-"+name);
return "error";
}

  consumer的调用传参(url拼接少量参数)

        //get传递单参
ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsGetD?id={id}&name={name}", HttpMethod.GET, null, String.class,1,"zsw");
//post传递单参
ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPostD?id={id}&name={name}", HttpMethod.POST, null, String.class,1,"zsw");
//put传递单参
Map<String,Object> map=new HashMap<>();
map.put("id",1);
map.put("name","zsw");
ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPutD?id={id}&name={name}", HttpMethod.PUT, null, String.class,map);
//delete传递单参
Map<String,Object> map=new HashMap<>();
map.put("id",1);
map.put("name","zsw");
ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsDeleteD?id={id}&name={name}", HttpMethod.DELETE, null, String.class,map); //返回内容
String result = resp.getBody();
System.out.println(result);

  使用map和直接写参数都可以。

 再介绍一下传json对象。

  首先登场的是provider方controller。

    //测试get
@RequestMapping(value = "detailsGet",method = RequestMethod.GET)
public String test01(@RequestBody Detail detail){
System.out.println("GET-"+detail);
return "error";
}
//测试post
@RequestMapping(value = "detailsPost",method = RequestMethod.POST)
public String test02(@RequestBody Detail detail){
System.out.println("POST-"+detail);
return "error";
}
//测试put
@RequestMapping(value = "detailsPut",method = RequestMethod.PUT)
public String test03(@RequestBody Detail detail){
System.out.println("PUT-"+detail);
return "error";
}
//测试delete
@RequestMapping(value = "detailsDelete",method = RequestMethod.DELETE)
public String test04(@RequestBody Detail detail){
System.out.println("DELETE-"+detail);
return "error";
}

  我们再来看consumer的选手,传参json对象。

        String json = "{\"author\":\"zsw\",\"createdate\":1582010438846,\"id\":1,\"summary\":\"牡丹\",\"title\":\"菏泽\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(json,headers);
ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPost", HttpMethod.POST, entity, String.class);
HttpStatus statusCode = resp.getStatusCode(); // 获取响应码
int statusCodeValue = resp.getStatusCodeValue(); // 获取响应码值
HttpHeaders headers1 = resp.getHeaders(); // 获取响应头
System.out.println("statusCode:" + statusCode);
System.out.println("statusCodeValue:" + statusCodeValue);
System.out.println("headers:" + headers1); //或者直接传对象,底层自己处理
Detail detail=new Detail();
detail.setId(1L);
detail.setSummary("牡丹");
detail.setTitle("菏泽");
detail.setAuthor("zsw");
detail.setCreatedate(new Timestamp(new Date().getTime()));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Detail> entity = new HttpEntity<>(detail,headers);
ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsDelete", HttpMethod.DELETE, entity, String.class); //拿到返回值
String result = resp.getBody();
System.out.println(result);
return result;

  post、put、delete请求都可以用这种方法。但是测试get时就不行了直接报错:org.springframework.web.client.HttpClientErrorException: 400 null(错误请求,服务器不理解请求的语法),get请求不支持这种方式的传参,get请求只能将请求参数拼接URI后边,而不能单独传递request body参数,除非你改用POST。如果用resuful风格,必须要get传参对象,也不是没有办法的。根据(https://blog.belonk.com/c/http_resttemplate_get_with_body.html)这篇文章,小弟把情况摸清楚了,上手!

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.zhou.entity.Detail;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate; import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map; @Repository
public class DetailMapper { public String test(){
RestTemplate restTemplate1 = new RestTemplate();
restTemplate1.setRequestFactory(new HttpComponentsClientHttpRequestWithBodyFactory()); String json = "{\"author\":\"zsw\",\"createdate\":1582010438846,\"id\":1,\"summary\":\"牡丹\",\"title\":\"菏泽\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(json,headers);
ResponseEntity<String> resp = restTemplate1.exchange("http://localhost:8080/detailsGet", HttpMethod.GET, entity, String.class); String result = resp.getBody();
System.out.println(result);
return result;
}
private static final class HttpComponentsClientHttpRequestWithBodyFactory extends HttpComponentsClientHttpRequestFactory {
@Override
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
if (httpMethod == HttpMethod.GET) {
return new HttpGetRequestWithEntity(uri);
}
return super.createHttpUriRequest(httpMethod, uri);
}
}
private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
public HttpGetRequestWithEntity(final URI uri) {
super.setURI(uri);
} @Override
public String getMethod() {
return HttpMethod.GET.name();
}
}
}

  大致就是这个样子。对于没接触过httpclient的我,有些类不能导包,属实有的懵。百度百度百度。。。  找到httpclient的maven的依赖,下载导包,成功!启动项目:无法访问org.apache.http.annotation.ThreadSafe,找不到org.apache.http.annotation.ThreadSafe的类文件 ???,我记忆中没有用过这个类,全局搜索一下也找不到(ctrl+shift+f  -  查询自己写的代码)。继续百度,说httpclient4.5.2版本和httpcore4.4.4版本更配哦,maven自动下载的httpcore4.4.13,今天这个maven咋回事(好感-1),参考(https://www.jianshu.com/p/f35eac56c334)文章,最终的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zhou</groupId>
<artifactId>news-consumer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>news-consumer</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 分页 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency> <!-- Apache Commons IO -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.4</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

  重新启动,访问,拿到参数。

附上github地址:https://github.com/wwck-zsw/RestTemplate

参考链接:

    https://segmentfault.com/a/1190000021123356

    https://www.cnblogs.com/jnba/p/10522608.html(灵感来源)

RestTemplate的exchange()方法,解决put和delete请求拿不到返回值的问题的更多相关文章

  1. SpringBoot 使用 RestTemplate 调用exchange方法 显示错误信息

    SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...

  2. Spring RestTemplate 之exchange方法

    ●exchange方法提供统一的方法模板进行四种请求:POST,PUT,DELETE,GET (1)POST请求 String reqJsonStr = "{\"code\&quo ...

  3. 自定义HttpMessageConverter实现RestTemplate的exchange方法返回自定义格式数据

    一 概述 实现如下效果代码,且可正常获取到返回数据: ResponseEntity<JsonObject> resEntity = restTemplate .exchange(url, ...

  4. 利用jquery的$.Deferred方法在一个函数内获取另一个函数的返回值

    使用场景:方法B需要方法A执行完成之后再执行,比如方法B中有用到方法A的变量:(需要引入jQuery1.5以后的版本) function A(){ var deffered = new $.Defer ...

  5. Java--FutureTask原理与使用(FutureTask可以被Thread执行,可以被线程池submit方法执行,并且可以监控线程与获取返回值)

    package com; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; i ...

  6. angularJS 条件查询 品优购条件查询品牌(条件查询和列表展示公用方法解决思路 及 post请求混合参数提交方式)

    Brand.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> &l ...

  7. 资料汇总--Ajax中Put和Delete请求传递参数无效的解决方法(Restful风格)【转】

    开发环境:Tomcat9.0 在使用Ajax实现Restful的时候,有时候会出现无法Put.Delete请求参数无法传递到程序中的尴尬情况,此时我们可以有两种解决方案:1.使用地址重写的方法传递参数 ...

  8. Ajax中Put和Delete请求传递参数无效的解决方法(Restful风格)

    本文装载自:http://blog.csdn.net/u012737182/article/details/52831008    感谢原文作者分享 开发环境:Tomcat9.0 在使用Ajax实现R ...

  9. CURL 支持 GET、PUT、POST、DELETE请求

    一个方法解决所有的 curl 请求的问题. <?php function curlTypeData( $method, $url, $data=false, $json=false ) { $d ...

随机推荐

  1. mysql 导入sql文件

    navicat 工具导入 1.连接数据库后,右键选择导入sql文件 2.选择sql文件,开始导入 4.过程图 5.结果图

  2. CSS学习笔记:定位属性position

    目录 一.定位属性简介 二.各属性值的具体功能 1. relative 2. absolute 3. fixed 三.三种定位属性的效果总结 参考资料:https://www.bilibili.com ...

  3. centos安装pm2报错

    报错信息: /usr/lib/node_modules/pm2/node_modules/chalk/source/index.js:103 ...styles, 这个问题其实很简单,就是npm和no ...

  4. 3D 穿梭效果?使用 CSS 轻松搞定

    背景 周末在家习惯性登陆 Apex,准备玩几盘.在登陆加速器的过程中,发现加速器到期了. 我一直用的腾讯网游加速器,然而点击充值按钮,提示最近客户端升级改造,暂不支持充值(这个操作把我震惊了~).只能 ...

  5. 如何系统学习C 语言(中)之 结构体篇

    1,结构体 在前面我们知道变量和数组都可以用来存储数据,变量用来存储单个数据,数组可以用来存储一组同类型的数据,但你有没有发现--它们都只适合单一属性的数据.那现实生活中,很多对象都是具有多属性的.例 ...

  6. C#简单配置类及数据绑定

    目录 简介 配置基类 派生配置类 数据绑定 Winform中的数据绑定 WPF下的数据绑定 附件 简介 本文实现一个简单的配置类,原理比较简单,适用于一些小型项目.主要实现以下功能: 保存配置到jso ...

  7. 问题 N: 非洲小孩

    题目描述 家住非洲的小孩,都很黑.为什么呢? 第一,他们地处热带,太阳辐射严重. 第二,他们不经常洗澡.(常年缺水,怎么洗澡.) 现在,在一个非洲部落里,他们只有一个地方洗澡,并且,洗澡时间很短,瞬间 ...

  8. 菜鸡的Java笔记 第四 - java 基础运算符

    数学运算符,逻辑运算,三目运算,位运算 double d2 = 314e2; //采用科学计数法的写法,表示10的2次方.= 31400.0 代码写的越简单越好   简化运算符 代码:x=x+y 可以 ...

  9. koa2使用ejs模板引擎

    在koa中使用ejs并不需要像在node中一样安装了还要引用,只需要npm了就行,同时还需要安装koa-views模块.如: const views = require('koa-views'); 对 ...

  10. NOIP2021游记(退役记)

    11月 13日 停课了 学了一上午+一晚上的分块. 下午月赛切掉两道题之后xzh发现E题是道树剖,果断开始切E. 结果: 做了快两个小时还是0分. 11月 14日 上午把黄题冲上了100,绿题冲上了5 ...