HttpUtils.java
8.67 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
package com.yoho.unions.utils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HttpUtils {
static Logger log = LoggerFactory.getLogger(HttpUtils.class);
//默认超时时间
private static final int DEFAULT_TIME_OUT = 6000;
//默认字符集
private static final String DEFAULT_CHAR_SET = "UTF-8";
/**
* 发送http请求,传输body
* @param url
* @param body
* @return
* @throws Exception
*/
public static Pair<Integer, String> postBody(String url, String body) throws Exception {
return postBody(url, body, null, DEFAULT_CHAR_SET, DEFAULT_TIME_OUT);
}
/**
* 发送http请求,传输body
* @param url
* @param body
* @return
* @throws Exception
*/
public static Pair<Integer, String> postJSON(String url, String body) throws Exception {
List<Header> headList = new ArrayList<Header>();
headList.add(new BasicHeader("Content-Type", "application/json"));
return postBody(url, body, headList, DEFAULT_CHAR_SET, DEFAULT_TIME_OUT);
}
/**
* 发送http请求,传输body
* @param url
* @param body
* @param charset
* @param timeout
* @return
* @throws Exception
*/
public static Pair<Integer, String> postJSON(String url, String body, String charset, int timeout) throws Exception {
List<Header> headList = new ArrayList<Header>();
headList.add(new BasicHeader("Content-Type", "application/json"));
return postBody(url, body, headList, charset, timeout);
}
/**
* 发送http请求,传输body
* @param url
* @param body
* @param headList
* @return
* @throws Exception
*/
public static Pair<Integer, String> postBody(String url, String body, List<Header> headList) throws Exception {
return postBody(url, body, headList, DEFAULT_CHAR_SET, DEFAULT_TIME_OUT);
}
/**
* 发送http请求,传输body
* @param url
* @param body
* @param headList
* @param charset
* @param timeout
* @return
* @throws Exception
*/
public static Pair<Integer, String> postBody(String url, String body, List<Header> headList, String charset, int timeout) throws Exception {
log.info("postBody with url={}, body={}", url, body);
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse re = null;
HttpPost post = null;
int code = 0;
String message = "";
try {
post = new HttpPost(url);
post.setEntity(new StringEntity(body, Charset.forName(charset)));
setConfig(post, headList, timeout);
long d1 = new Date().getTime();
re = client.execute(post);
code = re.getStatusLine().getStatusCode();
message = EntityUtils.toString(re.getEntity(), charset);
long d2 = new Date().getTime();
log.info("postBody with url={}, code={}, and cost time={}", url, code, (d2 - d1));
} catch (Exception e) {
log.error("postBody error with url={}, body={}", url, body, e);
throw e;
} finally {
if (re != null) {
EntityUtils.consume(re.getEntity());
re.close();
}
if (client != null) {
client.close();
}
}
return Pair.of(code, message);
}
/**
* 设置head和超时
* @param base
* @param headList
*/
private static void setConfig(HttpRequestBase base, List<Header> headList, int timeout) {
if (CollectionUtils.isNotEmpty(headList)) {
for (Header head : headList) {
base.setHeader(head.getName(), head.getValue());
}
}
RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();//设置请求和传输超时时间
base.setConfig(config);
}
/**
* 发送post请求
* @param url
* @param param
* @return
* @throws Exception
*/
public static Pair<Integer, String> httpPost(String url, Map<String, Object> param) throws Exception {
return httpPost(url, param, null, DEFAULT_CHAR_SET, DEFAULT_TIME_OUT);
}
/**
* 发送post请求
* @param url
* @param param
* @param headList
* @return
* @throws Exception
*/
public static Pair<Integer, String> httpPost(String url, Map<String, Object> param, List<Header> headList) throws Exception {
return httpPost(url, param, headList, DEFAULT_CHAR_SET, DEFAULT_TIME_OUT);
}
public static void main(String[] args) {
String body = "{\"currentPage\":1,\"groupID\":1,\"groupType\":\"dynamic\",\"pageSize\":10,\"query_where\":[{\"item\":\"crm__crm_rfm_total__last_order_time\",\"query\":[{\"op\":\">\",\"value\":\"2016-05-31 14:40:00\"}]}]}";
try {
Pair<Integer, String> pair = postJSON("http://123.206.79.151:8188/bigdata/crm/generateDataFile", body, "UTF-8", 15*60*1000);
System.out.println("pair= " + pair);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送http请求,传递参数
* @param url
* @param param
* @param headList
* @param charset
* @param timeout
* @return
* @throws Exception
*/
public static Pair<Integer, String> httpPost(String url, Map<String, Object> param, List<Header> headList, String charset, int timeout) throws Exception {
log.info("httpPost with url={}, param={}", url, param);
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse re = null;
HttpPost post = null;
int code = 0;
String message = "";
try {
post = new HttpPost(url);
if (param != null) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Entry<String, Object> entry : param.entrySet()) {
log.debug("请求参数 --> " + entry.getKey() + "=" + entry.getValue());
if (entry.getKey() == null || entry.getValue() == null) {
throw new Exception("键值不能为null" + entry.getKey() + "=" + entry.getValue());
}
list.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
post.setEntity(new UrlEncodedFormEntity(list, charset));
}
setConfig(post, headList, timeout);
long d1 = new Date().getTime();
re = client.execute(post);
code = re.getStatusLine().getStatusCode();
message = EntityUtils.toString(re.getEntity(), charset);
long d2 = new Date().getTime();
log.info("httpPost with url={}, code={}, and cost time={}", url, code, (d2 - d1));
} catch (Exception e) {
log.error("httpPost error with url={}, param={}", url, param, e);
throw e;
} finally {
if (re != null) {
EntityUtils.consume(re.getEntity());
re.close();
}
if (client != null) {
client.close();
}
}
return Pair.of(code, message);
}
/**
* get请求
* @param url
* @param headList
* @return
* @throws Exception
*/
public static Pair<Integer, String> httpGet(String url, List<Header> headList) throws Exception {
return httpGet(url, headList, DEFAULT_CHAR_SET, DEFAULT_TIME_OUT);
}
/**
* get请求
* @param url
* @param headList
* @param charset
* @param timeout
* @return
* @throws Exception
*/
public static Pair<Integer, String> httpGet(String url, List<Header> headList, String charset, int timeout) throws Exception {
log.info("httpGet with url={}", url);
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse re = null;
HttpGet get = null;
int code = 0;
String message = "";
try {
get = new HttpGet(url);
RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();//设置请求和传输超时时间
get.setConfig(config);
long d1 = new Date().getTime();
re = client.execute(get);
code = re.getStatusLine().getStatusCode();
message = EntityUtils.toString(re.getEntity(), charset);
long d2 = new Date().getTime();
log.info("httpGet with url={}, code={}, and cost time={}", url, code, (d2 - d1));
} catch (Exception e) {
log.error("httpGet error with url={}", url, e);
throw e;
} finally {
if (re != null) {
EntityUtils.consume(re.getEntity());
re.close();
}
if (client != null) {
client.close();
}
}
return Pair.of(code, message);
}
}