Spring boot 整合 RestTemplate实例
添加web依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
service层
package com.mf.service;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.google.gson.Gson;
import com.mf.util.ResponseBoxData;
@Service
public class HttpClient {
public ResponseBoxData client(String url, MultiValueMap<String, String> map) {
//获取Rest客户端实例
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
//headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//解决中文乱码
//headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//注:GET请求 创建HttpEntity时,请求体传入null即可
HttpEntity<MultiValueMap<String, String>> httpEntity =
new HttpEntity<MultiValueMap<String, String>>(map,headers);
//postForEntity():POST数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
//ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
/**
* 往 url发送 post请求 请求携带信息为entity时返回的结果信息
* 因为返回的是HttpEntity<MultiValueMap<String, String>>所以如果要得到字符串不能强转为String,可以exchange().getBody()获取字符串
* String.class是可以修改的,其实本质上就是在指定反序列化对象类型,这取决于你要怎么解析请求返回的参数
*/
String strbody = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class).getBody();
/**
* 由于获取到的是字符串,需要的是自定义对象
* 可以使用Gson转换
* toJson(entity)//实体转字符串
* fromJson(entity,entity.class)//字符串转实体
*/
Gson gson = new Gson();
ResponseBoxData boxData = gson.fromJson(strbody, ResponseBoxData.class);
return boxData;
}
}
控制层调用
@RestController
@RequestMapping("/pda")
public class PdaController {
@Resource
HttpClient httpClient;
@RequestMapping(value = "/getBoxData/{ctnNo}")
public ResponseBoxData getBoxData(@PathVariable("ctnNo") String requestStr) {
String url = "http://192.168.1.31:8080/posmodule/rest/autopackage/getBoxInfoByQR";
//一个Key对应多个Value,既一个键对应多个值的MultiValueMap
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("requestStr", requestStr);
System.err.println("-----获取箱数据------");
ResponseBoxData data = httpClient.client(url, map);
return data;
}
}
Good Luck