一、应用场景
在spring cloud微服务中spring cloud feign针对RestTemplate做了封装,只能针对servername的请求,请求一些第三方api如百度开放api,支付api等需要通过host/ip+port请求,因此需要新配置一个RestTemplate
@Bean
RestTemplate remoteRestTemplate(){
return new RestTemplate();
}
二、主要代码
不需要去字符串空格可以将replace操作删除
1.工具类
public class HttpUtils {
private static RestTemplate restTemplate = SpringBeanUtil.getBean("remoteRestTemplate", RestTemplate.class);
private static ObjectMapper objectMapper = SpringBeanUtil.getBean("goldMsgobjectMapper", ObjectMapper.class);
private HttpUtils() {
}
public static <T> T postJsonRequest(String url, Map<String, Object> bodyParams, TypeReference<T> responseType) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return postJsonRequest(url, headers, bodyParams, responseType);
}
public static <T> T postJsonRequest(String url, HttpHeaders headers, Map<String, Object> bodyParams, TypeReference<T> responseType) throws IOException {
HttpEntity formEntity = new HttpEntity(objectMapper.writeValueAsString(bodyParams), headers);
return objectMapper.readValue(
restTemplate.postForObject(url, formEntity, String.class)
.replace(" ", "")
.replace("\n", "")
.replace("\t", ""),
responseType);
}
public static <T> T postRequest(String url, MultiValueMap<String, Object> bodyParams, TypeReference<T> responseType) throws IOException {
return objectMapper.readValue(restTemplate.postForObject(url, bodyParams, String.class)
.replace(" ", "")
.replace("\n", "")
.replace("\t", ""),
responseType);
}
public static <T> T getRequest(String url, MultiValueMap<String, Object> headerParams, TypeReference<T> responseType) throws IOException {
return objectMapper.readValue(
restTemplate.getForObject(url, String.class, headerParams)
.replace(" ", "")
.replace("\n", "")
.replace("\t", ""),
responseType);
}
}
2.spring bean工具类
@Component
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(null==this.applicationContext) this.applicationContext = applicationContext;
}
public static <T> T getObject(Class<T> tClass) {
return applicationContext.getBean(tClass);
}
public static <T> T getBean(String tClassName, Class<T> tClass) {
return (T)applicationContext.getBean(tClassName);
}
public <T> T getBean(Class<T> tClass) {
return applicationContext.getBean(tClass);
}
}
3.配置objectMapper
我个人比较喜欢用的json库是jackson因为规范,而且全局配置一个ObjectMapper性能优于fastjson,gson等json库的
@Bean()
ObjectMapper goldMsgobjectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}