Java RestTemplate传递参数
Map<String, Object> paramMap = new HashMap<String, Object>(); Map<String, Object> paramMap = new LinkedHashMap<String, Object>();
经过测试,我发现这两种map里面的参数都不能被后台接收到,这个问题困扰我两天,终于,当我把Map类型换成LinkedMultiValueMap后,参数成功传递到后台。
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
注:HashMap是以请求体传递,MultiValueMap是表单传递。
经过测试,正确的POST传参方式如下
public static void main(String[] args) {
RestTemplate template = new RestTemplate();
String url = "http://192.168.2.40:8081/channel/channelHourData/getHourNewUserData";
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("dt", "20180416");
// 1、使用postForObject请求接口
String result = template.postForObject(url, paramMap, String.class);
System.out.println("result1==================" + result);
// 2、使用postForEntity请求接口
HttpHeaders headers = new HttpHeaders();
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
System.out.println("result2====================" + response2.getBody());
// 3、使用exchange请求接口
ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);
System.out.println("result3====================" + response3.getBody());
}
补充:POST传参对象
@Autowired
private RestTemplate restTemplate;
private String url="http://localhost:8080/users"; public Integer save(User user){
Map<String,String> map = restTemplate.postForObject(url, user, Map.class);
if(map.get("result").equals("success")){
//添加成功
return 1;
}
return -1;
} //这是访问的controller方法
@RequestMapping(value = "users",method = RequestMethod.POST)
public Map<String,String> save(@RequestBody User user){
Integer save = userService.save(user);
Map<String,String> map=new HashMap<>();
if(save>0){
map.put("result","success");
return map;
}
map.put("result","error");
return map;
}
ps:post请求也可以通过占位符的方式进行传参(类似get),但是看起来不优雅,推荐使用文中的方式。
GET方式传参说明
如果是get请求,又想要把参数封装到map里面进行传递的话,Map需要使用HashMap,且url需要使用占位符,如下:
public static void main(String[] args) {
RestTemplate restTemplate2 = new RestTemplate();
String url = "http://127.0.0.1:8081/interact/getData?dt={dt}&ht={ht}";
// 封装参数,这里是HashMap
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("dt", "20181116");
paramMap.put("ht", "10");
//1、使用getForObject请求接口
String result1 = template.getForObject(url, String.class, paramMap);
System.out.println("result1====================" + result1);
//2、使用exchange请求接口
HttpHeaders headers = new HttpHeaders();
headers.set("id", "lidy");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null,headers);
ResponseEntity<String> response2 = template.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap);
System.out.println("result2====================" + response2.getBody());
}
/**
* 删除用户
* @param id
* @return
*/
public String delete(Long id) {
StringBuffer url = new StringBuffer(baseUrl)
.append("/user/delete/{id}"); Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", id); ResponseEntity<String > response = restTemplate.exchange(url.toString(), HttpMethod.DELETE, null, String .class, paramMap);
String result = response.getBody(); return result;
}
补充:resultful风格直接拼接url
//负责调用provider的方法,获取数据
@Autowired
private RestTemplate restTemplate;
//在provider端资源的路径
private String url="http://localhost:8080/details"; public String deleteDetail(Integer id){
ResponseEntity<String> response = restTemplate.exchange(url + "/" + id, HttpMethod.DELETE, null, String.class);
String result = response.getBody();
return result;
} //被调用的controller方法
@ResponseBody
@RequestMapping(value = "details/{id}",method = RequestMethod.DELETE)
public String deleteDetail(@PathVariable Integer id){
Integer integer = detailService.deleteDetail(id);
if(integer>0){
return "success";
}
return "error";
}
不是resultful风格可以使用占位符
private String url="http://localhost:8080/details?id={id}";
public String deleteDetail(Integer id){
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", id);
ResponseEntity<String > response = restTemplate.exchange(url.toString(), HttpMethod.DELETE, null, String .class, paramMap);
String result = response.getBody();
return result;
}
put请求实例,请求方式使用 HttpMethod.PUT
/**
* 更新用户基础信息
* @param userInfoDTO
* @return
*/
public String edit(UserInfoDTO userInfoDTO) {
StringBuffer url = new StringBuffer(baseUrl)
.append("/user/edit?tmp=1")
.append("&id={id}")
.append("&userName={userName}")
.append("&nickName={nickName}")
.append("&realName={realName}")
.append("&sex={sex}")
.append("&birthday={birthday}"); Map<String, Object> paramMap = new HashMap<>();
paramMap.put("userId", userInfoDTO.getId());
paramMap.put("userName", userInfoDTO.getUserName());
paramMap.put("nickName", userInfoDTO.getNickName());
paramMap.put("realName", userInfoDTO.getRealName());
paramMap.put("sex", userInfoDTO.getSex());
paramMap.put("birthday", userInfoDTO.getBirthday()); ResponseEntity<String > response = restTemplate.exchange(url.toString(), HttpMethod.PUT, null, String .class, paramMap);
String result = response.getBody();
return result; }
//测试post的controller
@RequestMapping(value = "detailsPost",method = RequestMethod.POST)
public String test02(@RequestBody Detail detail){
System.out.println("POST-"+detail);
return "error";
}
//测试put的controller
@RequestMapping(value = "detailsPut",method = RequestMethod.PUT)
public String test03(@RequestBody Detail detail){
System.out.println("PUT-"+detail);
return "error";
}
//测试delete的controller
@RequestMapping(value = "detailsDelete",method = RequestMethod.DELETE)
public String test04(@RequestBody Detail detail){
System.out.println("DELETE-"+detail);
return "error";
} //测试方法
public String test(){
//put传递对象
//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/detailsPut", HttpMethod.PUT, entity, String.class); //delete传递对象
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;
}
delete请求和上面一样,但是get不行,直接报错400。好像是get不支持这种传参。https://blog.belonk.com/c/http_resttemplate_get_with_body.htm 和这大哥的情况一样,但是他的解决方案我没搞明白,so 如有大佬还望指点一下老弟,不胜感激。
exchange()传递单个参数可以使用占位符:
//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);
get、post、put、delete请求通用。
Java RestTemplate传递参数的更多相关文章
- Java方法传递参数传值还是传址的问题
这几天重构项目代码遇到一个疑问:可不可以在方法A中定义一个boolean变量b为false,然后A调用方法C把b传递到C方法中经过一些列业务判断后修改为true,C执行结束后A方法中b的值还是原来的f ...
- jquery ajax 用 data 和 headers 向 java RESTful 传递参数区别
jquery 的 ajax 是非常方便的一个函数,记录一下 $.ajax 生成的 http 报文 一.使用 data 传递参数: $.ajax({ url : "webrs/test/add ...
- Unity3D研究院之打开Activity与调用JAVA代码传递参数
原地址:http://www.xuanyusong.com/archives/667 Unity for Android 比较特殊,Unity for IOS 打包是将XCODE工程直接交给开发 ...
- JAVA中传递参数乱码问题
url传递中文如果jsp页面,myeclipse.web.xml中org.springframework.web.filter.CharacterEncodingFilter,都是UTF-8编码,直接 ...
- JAVA接口传递参数(POST),从接口接收数据(JSON) -----记录
1,给接口传递json格式的数据 import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOEx ...
- JAVA方法传递参数:传值?传引用?
先来看下面这三段代码: //Example1: public class Example1 { static void check(int a) { a++; } public static void ...
- jquery通过ajax-json访问java后台传递参数,通过request.getParameter获取不到参数的说明
http://m.blog.csdn.net/blog/eyebrother/36007145 所以当后台通过request.getParameter("name");对参数值的作 ...
- java调用python脚本并向python脚本传递参数
1.安装Eclipse 先安装jdk,再安装Eclipse,成功后开始建立py_java项目,在这个项目的存储目录SRC下建立test包,在test包中New-Class,新建MyDemo类,建好完成 ...
- SpringMVC中使用Ajax POST请求以json格式传递参数服务端通过request.getParameter("name")无法获取参数值问题分析
SpringMVC中使用Ajax POST请求以json格式传递参数服务端通过request.getParameter("name")无法获取参数值问题分析 一:问题demo展示 ...
随机推荐
- coding game, 边打游戏边学编程,是一种怎么样的体验?
前言 hello,大家好,我是bigsai,好久不见,甚是想念! 在日常生活中,很多人喜欢玩游戏,因为游戏中有着对抗博弈.控制的喜悦,用灵魂指法完成一波靓丽的操作. 但实际上,你的按键都是对应代码中一 ...
- The Ninth Week (Lucklyzpp)
The Ninth Week (Lucklyzpp) 1.简述DNS服务器原理,并搭建主-辅服务器. [10:36:39 root@lucklyzpp ~]#vim /etc/named.conf ...
- selet 语句详解
SELECT 语句的基本格式为: SELECT 要查询的列名 FROM 表名字 WHERE 限制条件; 2.0 数学符号条件 SELECT 语句常常会 ...
- [atARC111F]Do you like query problems
(以下修改指1和2类操作,询问指3类操作,操作指修改或询问) 注意到总方案数确定,那么不妨求出答案的期望,再乘上方案数即为答案 (这里从期望的角度考虑只是为了描述方便,并没有太大的实际意义) 设$E( ...
- ElasticJob分布式任务调度应用v2.5.2
为何要使用分布式任务调度 **本人博客网站 **IT小神 www.itxiaoshen.com 演示项目源码地址** https://gitee.com/yongzhebuju/spring-task ...
- selenium定位元素方法汇总
#打开网页前三步 from selenium import webdriver driver=webidriver.Chrome() driver.get("https://www.baid ...
- Qt5 connect 重载信号和槽
转载文章超哥的经验之谈---Qt5 connect使用之"重载信号和槽" 在Qt4中,关联信号与槽是要使用到SIGNAL()和SLOT()这两个宏. QLabel *label = ...
- [linux] rm -rf删除软链接无权限?
一个很简单的命令,使用频率非常高,但一没注意就会失策. 我将别人盘下的list目录软连接到自己盘中,想要删除时: rm -rf list/ #输入时自然地用tab键补全 结果: 试了多次也删除不了,最 ...
- js变量作为数组对象的键值方法
js变量作为数组对象的键值方法,变量键值获取数组值 js也可以像php的数组一样用下标获取数组的值,方法是: var arr = {'key':'abc'}; var key = 'key'; con ...
- Excel-计算年龄、工龄 datedif()
函数名称:DATEDIF 主要功能:计算返回两个日期参数的差值. 使用格式:=DATEDIF(date1,date2,"y").=DATEDIF(date1,date2," ...