工具类MedicalHttpUtil
package com.bill99.seashell.domain.common.insure.util;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MedicalHttpUtil {
protected static Logger log = LoggerFactory.getLogger(MedicalHttpUtil.class);
/**
* Http request :Post
*
* @param requestObject
* @param serviceId
* @param url
* @param timeOut (Millisecond)
* @return result map
*/
public static String postHttpRequest(Object requestObject, String url) throws Exception{
return postHttpRequest(requestObject, url, 60 * 1000);
}
/**
* Http request :Post
*
* @param requestObject
* @param serviceId
* @param url
* @param timeOut (Millisecond)
* @return result map
*/
public static String postHttpRequest(Object requestObject, String url, Integer timeOut) throws Exception{
CloseableHttpResponse response = null;
try {
String reqeustString = "[]";
if (requestObject != null) {
reqeustString=convert2Json(requestObject);
}
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//httpPost.addHeader("x-service-id", serviceId);
// set Timeout
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut)
.setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
httpPost.setConfig(requestConfig);
httpPost.setEntity(new StringEntity(reqeustString, ContentType.APPLICATION_JSON));
response = httpclient.execute(httpPost);
// get http status code
int resStatu = response.getStatusLine().getStatusCode();
String responseString = null;
if (resStatu == HttpStatus.SC_OK ) {
responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
throw new Exception(Arrays.toString(response.getHeaders("x-service-message")));
}
return responseString;
} catch (Exception e) {
log.error("Error", e);
throw e;
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
response.close();
} catch (Exception e) {
log.error("Error", e);
}
}
}
}
public static String convert2Json(Object object) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
objectMapper.writeValue(byteArrayOutputStream, object);
return byteArrayOutputStream.toString();
}
@SuppressWarnings("unchecked")
public static Map<String, Object> jsonToMap(String jsonString) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(jsonString, Map.class);
}
@SuppressWarnings("unchecked")
public static List<Object> jsonToList(String jsonString) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(jsonString, List.class);
}
}
工具类的使用:
//调用爱立方接口
Object requestObject = buildALFFreeRequest(atpMedicalOrderDto);
if(requestObject == null){
logger.info("构建爱立方接口请求参数为空");
handlerResponse.setRespInfo(FpdErrInfo.REQ_INFO_EMPTY);
return handlerResponse;
}
logger.info("爱立方请求参数:"+JsonUtils.objectToJson(requestObject));
try{
String url = DynamicConfigLoader.get(ALF_serviceUrl);
String responseString = MedicalHttpUtil.postHttpRequest(requestObject, url);
Map<String, Object> resultMap = HttpUtil.jsonToMap(responseString);
logger.info("爱立方响应参数:"+JsonUtils.objectToJson(resultMap));
String returnFlag = resultMap.get("ReturnFlag").toString();
if(!StringUtil.isEmpty(returnFlag)&&"01".equals(returnFlag)){//如果返回为处理成功
atpMedicalRightService.updateMedicalOrderStatus(atpMedicalOrderDto.getOrderId(),MedicalStatus.PAY_SUCC.val(),MedicalStatus.APPLY_SUCC.val());
}else{
String returnInfo = java.net.URLDecoder.decode(resultMap.get("ReturnInfo").toString(), "UTF-8");
atpMedicalOrderDto.setErrorCode(returnFlag);
atpMedicalOrderDto.setErrorMsg(returnInfo);
atpMedicalOrderDto.setStatus(MedicalStatus.APPLY_HANDLE.val());
atpMedicalRightService.saveMedicalOrder(atpMedicalOrderDto);
}
}catch(Exception ex) {
logger.error("调用爱立方接口异常", ex);
atpMedicalOrderDto.setErrorCode(FpdErrInfo.SYS_ERR.code());
atpMedicalOrderDto.setErrorMsg("调用爱立方接口异常");
atpMedicalOrderDto.setStatus(MedicalStatus.APPLY_HANDLE.val());
atpMedicalRightService.saveMedicalOrder(atpMedicalOrderDto);
}