一、應(yīng)用場(chǎng)景
在spring cloud微服務(wù)中spring cloud feign針對(duì)RestTemplate做了封裝,只能針對(duì)servername的請(qǐng)求,請(qǐng)求一些第三方api如百度開放api,支付api等需要通過(guò)host/ip+port請(qǐng)求,因此需要新配置一個(gè)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
我個(gè)人比較喜歡用的json庫(kù)是jackson因?yàn)橐?guī)范,而且全局配置一個(gè)ObjectMapper性能優(yōu)于fastjson,gson等json庫(kù)的
@Bean()
ObjectMapper goldMsgobjectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}