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展示 ...
随机推荐
- TypeScript 泛型及应用
TypeScript 泛型及应用 一.泛型是什么 二.泛型接口 三.泛型类 四.泛型约束 4.1 确保属性存在 4.2 检查对象上的键是否存在 五.泛型参数默认类型 六.泛型条件类型 七.泛型工具类型 ...
- Jenkins执行 remote SSH 命令
1.安装 SSH Pipeline Steps 插件 2.在凭据中添加remote server凭据,如下 3.Pipeline编写: def GetRemoteServer(ip){ def rem ...
- [atARC121E]Directed Tree
令$b_{a_{i}}=i$,那么问题即要求$i$不是$b_{i}$的祖先,也即$b_{i}$不严格在$i$的子树中 显然$a_{i}$和$b_{i}$一一对应,因此我们不妨统计$b_{i}$的个数 ...
- [loj3347]有趣的旅途
考虑求出重心,以0为根建树,求出第 $i$个点的子树大小$sz[i]$($a(0,i)$),则满足$n-sz[i]\le \lfloor\frac{n}{2}\rfloor$的$sz[i]$中的最小值 ...
- class动态样式绑定
字符串,数组,对象
- js防止重复提交代码
if (checkSubmitFlg == true) { console.log("禁止频繁操作.."); layer.close(ide); return false; } c ...
- .net打独立运行环境遇到无法trim遇到的bug
背景介绍 工作中我用到kotlin写代码,在orm上ktorm是一款非常优秀的操作db的框架,我喜欢用它所以我写了一个插件能够增加我的工作效率,这款idea插件的主体逻辑是.net开发的(没错是跨平台 ...
- CF1175G
叉姐牛逼. \(f_{k,i} = \min_{0\leq j <i}{f_{k - 1,j} + RMQ(j + 1,i) * (i - j)}\) 我们考虑在序列上分治一波. 按照\(m\) ...
- Codeforces 1365G - Secure Password(思维题)
Codeforces 题面传送门 & 洛谷题面传送门 首先考虑一个询问 \(20\) 次的方案,考虑每一位,一遍询问求出下标的这一位上为 \(0\) 的位置上值的 bitwise or,再一遍 ...
- Codeforces 521E - Cycling City(点双连通分量+分类讨论)
Codeforces 题面传送门 & 洛谷题面传送门 大家都是暴力找生成树然后跳路径,代码不到 50 行(暴论)的一说--好,那本蒟蒻决定提供一种代码 150 行,但复杂度也是线性的分类讨论做 ...