用restTemplate 的post传递参数时用以下方法设置:
RestTemplate resetTemplate = new RestTemplate();
MultiValueMap<String, String> requestMap= new LinkedMultiValueMap<String, String>();
requestMap.add("client_id", "123");
requestMap.add("app_code", "abc");
HttpEntity requestEntity = new HttpEntity(requestMap,null);
String responseAsString = resetTemplate.postForObject(url,requestEntity,String.class);
参数是放在HttpEntity中发送,与get方法不一样。如果要post一个json串,则使用如下方式:
RestTemplate resetTemplate = new RestTemplate();
MultiValueMap<String, String> requestMap= new LinkedMultiValueMap<String, String>();
requestMap.add("client_id", "123");
requestMap.add("app_code", "abc");
// 必须加上header说明
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
Gson gson = new Gson();
HttpEntity<String> requestEntity = new HttpEntity<String>(gson.toJson(requestMap),headers);
String responseAsString = resetTemplate.postForObject(url,requestEntity,String.class);
这时在服务器端应该用recv(@RequestBody App app)来接收参数,类App应包含属性client_id,app_code。
如果服务器端返回的是一个二进制流,则用如下方法处理:
ResponseEntity<byte[]> result = resetTemplate.getForEntity(url,byte[].class);
byte[] data = result.getBody();
网友评论