GatewayHttpUtils.java 1.95 KB
package com.bsth.data.directive;

import java.io.IOException;

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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.bsth.util.ConfigUtil;

/**
 * 
 * @ClassName: GatewayHttpUtils 
 * @Description: TODO(和网关HTTP通讯工具类) 
 * @author PanZhao
 * @date 2016年8月14日 下午9:50:46 
 *
 */
public class GatewayHttpUtils {
	static Logger logger = LoggerFactory.getLogger(GatewayHttpUtils.class);
	
	static String url;
	
	static{
		url = ConfigUtil.get("http.send.directive");
	}
	
	public static  int postJson(String jsonStr){
		logger.info("send : " + jsonStr);
		
		CloseableHttpClient httpClient = null;
		int code = -1;
		try{
			httpClient = HttpClients.createDefault();
			
			//超时时间
			RequestConfig requestConfig = RequestConfig.custom()  
			        .setConnectTimeout(3000).setConnectionRequestTimeout(1000)  
			        .setSocketTimeout(3000).build();
			
			HttpPost post = new HttpPost(url);
			
			post.setConfig(requestConfig);
			
			post.setEntity(new StringEntity(jsonStr, "utf-8"));
		
			CloseableHttpResponse response = httpClient.execute(post);
			
			JSONObject json = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
			if(null != json && json.getInteger("errCode") == 0)
				code = 0;
			else
				logger.error("和网关http通讯失败,rs: " + json);
		}catch(Exception e){
			logger.error("", e);
		}finally {
			try {
				if(httpClient != null)
					httpClient.close();
			} catch (IOException e) {
				logger.error("", e);
			}
		}
		return code;
	}
}