GatewayHttpUtils.java
2.45 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
74
75
package com.bsth.data.directive;
import com.alibaba.fastjson.JSONObject;
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 org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author PanZhao
* @ClassName: GatewayHttpUtils
* @Description: TODO(和网关HTTP通讯工具类)
* @date 2016年8月14日 下午9:50:46
*/
@Component
public class GatewayHttpUtils implements InitializingBean {
static Logger logger = LoggerFactory.getLogger(GatewayHttpUtils.class);
static String url;
static CloseableHttpClient httpClient = null;
static HttpPost post;
static RequestConfig requestConfig;
static CloseableHttpResponse response;
public static int postJson(String jsonStr) {
logger.info("send : " + jsonStr);
int code = -1;
try {
post.setEntity(new StringEntity(jsonStr, "utf-8"));
response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != 200){
logger.error("http client status code: " + statusCode);
}
JSONObject json = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
if (null != json && json.getInteger("errCode") == 0)
code = 0;
else
logger.error("和网关http通讯失败,rs: " + json);
if (null != response)
response.close();
} catch (Exception e) {
logger.error("", e);
}
return code;
}
@Value("${http.send.directive}")
public void setUrl(String url) {
GatewayHttpUtils.url = url;
}
@Override
public void afterPropertiesSet() throws Exception {
httpClient = HttpClients.createDefault();
post = new HttpPost(url);
requestConfig = RequestConfig.custom()
.setConnectTimeout(3000).setConnectionRequestTimeout(2000)
.setSocketTimeout(3000).build();
post.setConfig(requestConfig);
}
}