java的httppost请求

工具类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);
		}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用Java发送POST请求的示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class HttpPostExample { public static void main(String[] args) { try { String url = "http://example.com/api"; String payload = "key1=value1&key2=value2"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置HTTP请求方法为POST con.setRequestMethod("POST"); // 设置请求头信息 con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 启用输出流 con.setDoOutput(true); // 创建输出流写入POST请求参数 OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream()); writer.write(payload); writer.flush(); writer.close(); // 获取服务器响应 int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 输出响应结果 System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 其中,`url`为请求的URL地址,`payload`为POST请求的参数。在示例中,POST请求的参数是以`key1=value1&key2=value2`的形式拼接的,如果需要传递JSON数据,则可以将JSON序列化为字符串作为POST请求参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值