RestTemplate进行httpPost访问

通过RestTemplate访问实现了代码优雅简介的访问http请求,去掉了通过httplient繁琐的流程

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
* restTemplate包装工具
*
* @author lichuang
* @since 2018-04-05
*/
public class RestTemplateUtil {

private static final Logger logger = LoggerFactory.getLogger(RestTemplateUtil.class);

private static final String CHARSET_NAME = "UTF-8";

private static final String MEDIA_TYPE = "application/json; charset=UTF-8";

/**
*
* @param url 请求URL地址
* @param paramMap 请求参数
* @param clazz 需要返回的类型
* @param 需要返回的包装类型泛型
* @return
*/
public static T httpPost(String url, Map paramMap, Class clazz) {
if (CollectionUtils.isEmpty(paramMap)) {
paramMap = new HashMap<>();
}
String jsonParam = JSON.toJSONString(paramMap);
StringHttpMessageConverter messageConverter = new StringHttpMessageConverter(Charset.forName(CHARSET_NAME));
RestTemplate restTemplate = new RestTemplateBuilder().additionalMessageConverters(messageConverter).build();
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType(MEDIA_TYPE);
headers.setContentType(type);
HttpEntity entity = new HttpEntity(jsonParam,headers);
try {
String result = restTemplate.postForObject(url, entity, String.class);
return JSON.parseObject(result,clazz);
} catch (Exception e) {
logger.error("远程http请求发生异常:url:{},jsonParm:{},exception:{}",url,jsonParam,e);
return null;
}
}
}

你可能感兴趣的:(RestTemplate)