RestTemple是Spring提供的用于访问Http请求的客户端;
相对于apache的HTTPClient类,逻辑繁琐,代码复杂,还要自己编写使用类HttpClientUtil,封装对应的post,get,delete等方法。
RestTemplate可以通过callback回调方法和配置HttpMessageConverter 来定制,用来把对象封装到HTTP请求体,将响应信息放到一个对象中。RestTemplate提供更高等级的符合HTTP的六种主要方法,可以很简单的调用RESTful服务。
方法名称:exchange(String url, HttpMethod method,@Nullable HttpEntity<?> requestEntity, Class responseType, Map uriVariables)
说明:1)url: 请求地址;
2)method: 请求类型(如:POST,PUT,DELETE,GET);
3)requestEntity: 请求实体,封装请求头,请求内容
4)responseType: 响应类型,根据服务接口的返回类型决定
5)uriVariables: url中参数变量值
private String getId(String id) {
String url = RemoteUrl + "/id";
//设置Http的Header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//设置访问参数
HashMap<String, Object> params = new HashMap<>();
params.put("name", name);
//设置访问的Entity
HttpEntity entity = new HttpEntity<>(params, headers);
ResponseEntity<String> result = null;
try {
//发起一个POST请求
result = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
JSONObject data = JSONObject.parseObject(result.getBody()).getJSONObject("data");
return data.getString("id");
} catch (Exception e) {
logger.error("获取id失败: " + e.getMessage());
}
return null;
}
String reqJsonStr = "{\"id\":227,\"code\":\"updateCC\", \"group\":\"UPDATE\",\"content\":\"updateCT\", \"order\":9}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr,headers);
ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL, HttpMethod.PUT, entity, Map.class);
ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL + "?id={id}", HttpMethod.DELETE, null, Map.class, 227);
ResponseEntity<String> results = restTemplate.exchange(url,HttpMethod.GET, null, String.class, params);
@Slf4j
@Service
public class HttpUtils {
@Autowired
RestTemplate restTemplate;
public String postForString(String url, HttpMethod method, HttpEntity<?> requestEntity) throws FailException, ProxyException {
try {
ResponseEntity<String> result = restTemplate.exchange(url, method, requestEntity, String.class);
if (HttpStatus.OK.equals(result.getStatusCode())) {//当相应状态为200
return result.getBody();
} else {
throw new FailException("http调用失败:", result.getBody());
}
} catch (RestClientException e) {
throw new ProxyException(e);
}
}
}
静态变量/类变量不是对象的属性,而是一个类的属性,spring则是基于对象层面上的依赖注入。所以我们不能@Autowired或者@resource一个静态变量,使之成为一个spring bean。但是静态方法又不能调用非静态的属性。
所以要维护一个工具类的静态实例,初始化的时候把restTemplate传进来,这样就可以直接调用HttpUtil.httpRequest()方法。
@Component
public class HttpUtil {
private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
@Resource
private RestTemplate restTemplate;
private static HttpUtil httpUtil;
@PostConstruct
public void init(){
httpUtil = this;
httpUtil.restTemplate = this.restTemplate;
}
public static <T> String httpRequest(String url, HttpMethod method, HttpEntity<T> entity){
try {
//发起一个POST请求
ResponseEntity<String> result = httpUtil.restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
return result.getBody();
} catch (Exception e) {
logger.error("请求失败: " + e.getMessage());
}
return null;
}
}