HttpUtils.java 1.6 KB
package com.bsth.vehicle.directive.util;

import java.io.IOException;

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.vehicle.directive.Consts;

/**
 * 
 * @ClassName: HttpUtils 
 * @Description: TODO(和网关HTTP通讯工具类) 
 * @author PanZhao
 * @date 2016年7月8日 上午10:38:10 
 *
 */
public class HttpUtils {

	static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
	
	public static  int postJson(String jsonStr){
		logger.info("send : " + jsonStr);
		
		CloseableHttpClient httpClient = null;
		int code = -1;
		try{
			httpClient = HttpClients.createDefault();
			
			HttpPost post = new HttpPost(Consts.SEND_DIRECTIVE_URL);
			
			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;
	}
}