HttpUtils.java
14.5 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package com.glsx.common.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
/**
* http请求
* @
*
*/
public class HttpUtils {
int i=0;
private Logger logger = LoggerFactory.getLogger(HttpUtils.class);
/**
* post请求 ,超时默认10秒, 默认utf-8
* @param url
* @param params
* @return
* @throws IOException
*/
@SuppressWarnings("deprecation")
public String post(String url, Map<String, String> params) throws Exception {
return this.post(url, params, 10, HTTP.UTF_8);
}
/**
* post请求, 超时默认10秒
* @param url
* @param params
* @param charset 编码方式
* @return
* @throws Exception
*/
public String post(String url, Map<String, String> params, String charset) throws Exception {
return this.post(url, params, 10, charset);
}
public String postSms(String url, Map<String, String> params, String charset) throws Exception {
return this.postsms(url, params, 10, charset);
}
/**
* post请求, 默认utf-8
* @param url
* @param params
* @param timeout 超时时间,秒
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
public String post(String url, Map<String, String> params, int timeout) throws Exception {
return this.post(url, params, timeout, HTTP.UTF_8);
}
/**
* post请求
* @param url
* @param params
* @param timeout 超时时间,秒
* @return
* @throws IOException
*/
public String post(String url, Map<String, String> params, int timeout, String charset) throws Exception {
// if(logger.isInfoEnabled()){
// logger.info("connection url = " +url);
// logger.info("params = "+params.toString());
// }
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setIntParameter("http.socket.timeout", timeout * 1000);
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
String retVal = "";
try {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
if (params != null) {
for (Map.Entry<String, String> param : params.entrySet()) {
formparams.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, charset);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(entity);
HttpResponse resp = httpclient.execute(httppost);
retVal = EntityUtils.toString(resp.getEntity(), charset);
} catch (IOException e) {
logger.error(" post error : ", e);
throw e;
} finally {
httpclient.getConnectionManager().shutdown();
if(logger.isInfoEnabled()){
// logger.info("connection end,sartTime = "+startTime+" , endTime =" + endTime +" , times:"+(endTime-startTime));
}
}
return retVal;
}
/**
* post请求
* @param url
* @param params
* @param timeout 超时时间,秒
* @return
* @throws ParseException
* @throws IOException
*/
@SuppressWarnings({ "deprecation", "resource" })
public String postJson(String url,String json) throws Exception{
String retVal = "";
DefaultHttpClient httpClient =null;
if(url.contains("https")){
httpClient = new SSLClient();
}else{
httpClient = new DefaultHttpClient();
}
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
StringEntity se = new StringEntity(json.toString(),"UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
HttpResponse resp = httpClient.execute(httpPost);
retVal = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
return retVal;
}
/**
* 发送post请求到Google短链接服务器,获取url的短链接
* @param url
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
public String postGoogleURLShortener(String url) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setIntParameter("http.socket.timeout", 10000);
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
String retVal = url;
try {
HttpPost httppost = new HttpPost("https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyABoOMQswr72iix40kj1I42Dk7tBf0kppk");
httppost.setHeader("Content-Type", "application/json");
httppost.setEntity(new StringEntity("{\"longUrl\": \"" + url + "\"}"));
HttpResponse resp = httpclient.execute(httppost);
String jsonStr = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
if (StringUtils.isNotEmpty(jsonStr)) {
JSONObject jsonObj = JSONObject.parseObject(jsonStr);
if (jsonObj.containsKey("id")) {
retVal = jsonObj.getString("id");
}
}
} catch (IOException e) {
throw e;
} finally {
httpclient.getConnectionManager().shutdown();
}
return retVal;
}
/**
* get请求
* @param url
* @param params
* @param timeout 超时时间,秒
* @param charset 编码方式
* @return
* @throws Exception
*/
public static String get(String url, Map<String, String> params, int timeout, String charset) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setIntParameter("http.socket.timeout", timeout * 1000);
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
String retVal = "";
try {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
if (params != null) {
for (Map.Entry<String, String> param : params.entrySet()) {
qparams.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
}
String paramstr = URLEncodedUtils.format(qparams, charset);
if (StringUtils.isNotEmpty(paramstr)) {
url = url + "?" + paramstr;
}
HttpGet httpget = new HttpGet(url);
HttpResponse resp = httpclient.execute(httpget);
retVal = EntityUtils.toString(resp.getEntity(), charset);
} catch (IOException e) {
throw e;
} finally {
httpclient.getConnectionManager().shutdown();
}
return retVal;
}
/**
* get请求
* @param url
* @param params
* @param timeout 超时时间,秒
* @param charset 编码方式
* @param fNameEndChar 方法名后结束字符 默认“?”
* @return
* @throws Exception
*/
public static String get(String url, Map<String, String> params, int timeout, String charset,String fNameEndChar) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setIntParameter("http.socket.timeout", timeout * 1000);
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
String retVal = "";
fNameEndChar=(fNameEndChar==null || "".endsWith(fNameEndChar))? "?":fNameEndChar;
try {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
if (params != null) {
for (Map.Entry<String, String> param : params.entrySet()) {
qparams.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
}
String paramstr = URLEncodedUtils.format(qparams, charset);
if (StringUtils.isNotEmpty(paramstr)) {
url = url + fNameEndChar + paramstr;
}
HttpGet httpget = new HttpGet(url);
HttpResponse resp = httpclient.execute(httpget);
retVal = EntityUtils.toString(resp.getEntity(), charset);
} catch (IOException e) {
throw e;
} finally {
httpclient.getConnectionManager().shutdown();
}
return retVal;
}
/**
* get请求,超时默认10秒
* @param url
* @param params
* @param charset 编码方式
* @return
* @throws IOException
*/
public String get(String url, Map<String, String> params, String charset) throws Exception {
return this.get(url, params, 10, charset);
}
/**
* get请求,超时默认10秒, 默认utf-8
* @param url
* @param params
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
public static String get(String url, Map<String, String> params) throws Exception {
return get(url, params, 10, HTTP.UTF_8);
}
/**
* get请求, 默认utf-8
* @param url
* @param params
* @param timeout 超时时间,秒
* @return
* @throws Exception
*/
@SuppressWarnings("deprecation")
public String get(String url, Map<String, String> params, int timeout) throws Exception {
return this.get(url, params, timeout, HTTP.UTF_8);
}
public String postXml(String url,byte[] b,int timeout,String charset){
String retVal="";
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setIntParameter("http.socket.timeout", timeout * 1000);
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
HttpPost httppost = new HttpPost(url);
ByteArrayEntity entity=new ByteArrayEntity(b);
httppost.setEntity(entity);
HttpResponse resp = httpclient.execute(httppost);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpentity = resp.getEntity();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpentity.getContent(), "GBK"));
String line="";
while((line = bufferedReader.readLine())!=null) {
retVal += line;
}
bufferedReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return retVal;
}
@SuppressWarnings("deprecation")
public String postsms(String url, Map<String, String> params, int timeout, String charset) throws IOException {
long startTime = System.currentTimeMillis();
// if(logger.isInfoEnabled()){
// logger.info("connection url = " +url);
// logger.info("params = "+params.toString());
// }
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setIntParameter("http.socket.timeout", timeout * 1000);
httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
// httpclient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
String retVal = "";
try {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
if (params != null) {
for (Map.Entry<String, String> param : params.entrySet()) {
formparams.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, charset);
HttpPost httppost = new HttpPost(url);
httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler(10,false));
httppost.setEntity(entity);
HttpResponse resp = httpclient.execute(httppost);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpentity = resp.getEntity();
String httpcharset = EntityUtils.getContentCharSet(entity);
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpentity.getContent(), httpcharset));
String line="";
while((line = bufferedReader.readLine())!=null) {
retVal += line;
}
bufferedReader.close();
}
// retVal = EntityUtils.toString(resp.getEntity(), charset);
} catch (IOException e) {
i++;
if(i<=3){
postsms(url,params,timeout,charset);
}
logger.error(" post error : "+" url:"+url+" params"+params, e);
throw e;
} finally {
httpclient.getConnectionManager().shutdown();
long endTime = System.currentTimeMillis();
if(logger.isInfoEnabled()){
logger.info("connection end,sartTime = "+startTime+" , endTime =" + endTime +" , times:"+(endTime-startTime));
}
}
logger.info(" url:"+url+" params"+params);
logger.info("post back"+retVal);
return retVal;
}
}