GatewayHttpUtils.java
1.95 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
61
62
63
64
65
66
67
68
69
70
71
72
73
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;
}
}