HttpUtils.java
1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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;
}
}