/
HttpClient.java
730 lines (640 loc) · 22.5 KB
/
HttpClient.java
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
package com.kids21.app.newpaper.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.NoHttpResponseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import android.util.Log;
import com.kids21.app.newpaper.Configuration;
/**
* Wrap of org.apache.http.impl.client.DefaultHttpClient
*
* @author lds
*
*/
public class HttpClient {
private static final String TAG = "HttpClient";
private final static boolean DEBUG = Configuration.getDebug();
/** OK: Success! */
public static final int OK = 200;
/** Not Modified: There was no new data to return. */
public static final int NOT_MODIFIED = 304;
/**
* Bad Request: The request was invalid. An accompanying error message will
* explain why. This is the status code will be returned during rate
* limiting.
*/
public static final int BAD_REQUEST = 400;
/** Not Authorized: Authentication credentials were missing or incorrect. */
public static final int NOT_AUTHORIZED = 401;
/**
* Forbidden: The request is understood, but it has been refused. An
* accompanying error message will explain why.
*/
public static final int FORBIDDEN = 403;
/**
* Not Found: The URI requested is invalid or the resource requested, such
* as a user, does not exists.
*/
public static final int NOT_FOUND = 404;
/**
* Not Acceptable: Returned by the Search API when an invalid format is
* specified in the request.
*/
public static final int NOT_ACCEPTABLE = 406;
/**
* Internal Server Error: Something is broken. Please post to the group so
* the Weibo team can investigate.
*/
public static final int INTERNAL_SERVER_ERROR = 500;
/** Bad Gateway: Weibo is down or being upgraded. */
public static final int BAD_GATEWAY = 502;
/**
* Service Unavailable: The Weibo servers are up, but overloaded with
* requests. Try again later. The search and trend methods use this to
* indicate when you are being rate limited.
*/
public static final int SERVICE_UNAVAILABLE = 503;
private static final int CONNECTION_TIMEOUT_MS = 30 * 1000;
private static final int SOCKET_TIMEOUT_MS = 30 * 1000;
public static final int RETRIEVE_LIMIT = 20;
public static final int RETRIED_TIME = 3;
private static final String SERVER_HOST = "api.kids21.com";
private DefaultHttpClient mClient;
private AuthScope mAuthScope;
private BasicHttpContext localcontext;
private String mUserId;
private String mPassword;
public static String baseURL = Configuration.getScheme() + "192.168.1.23:8888/phpcms/";
private static boolean isAuthenticationEnabled = false;
public HttpClient() {
prepareHttpClient();
}
/**
* @param user_id
* auth user
* @param password
* auth password
*/
public HttpClient(String user_id, String password) {
prepareHttpClient();
setCredentials(user_id, password);
}
/**
* Empty the credentials
*/
public void reset() {
setCredentials("", "");
}
/**
* @return authed user id
*/
public String getUserId() {
return mUserId;
}
/**
* @return authed user password
*/
public String getPassword() {
return mPassword;
}
/**
* @param hostname
* the hostname (IP or DNS name)
* @param port
* the port number. -1 indicates the scheme default port.
* @param scheme
* the name of the scheme. null indicates the default scheme
*/
public void setProxy(String host, int port, String scheme) {
HttpHost proxy = new HttpHost(host, port, scheme);
mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
public void removeProxy() {
mClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
}
private void enableDebug() {
Log.d(TAG, "enable apache.http debug");
java.util.logging.Logger.getLogger("org.apache.http").setLevel(
java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(
java.util.logging.Level.FINER);
java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(
java.util.logging.Level.OFF);
/*
* System.setProperty("log.tag.org.apache.http", "VERBOSE");
* System.setProperty("log.tag.org.apache.http.wire", "VERBOSE");
* System.setProperty("log.tag.org.apache.http.headers", "VERBOSE");
*
* 在这里使用System.setProperty设置不会生效, 原因不明, 必须在终端上输入以下命令方能开启http调试信息: > adb
* shell setprop log.tag.org.apache.http VERBOSE > adb shell setprop
* log.tag.org.apache.http.wire VERBOSE > adb shell setprop
* log.tag.org.apache.http.headers VERBOSE
*/
}
/**
* Setup DefaultHttpClient
*
* Use ThreadSafeClientConnManager.
*
*/
private void prepareHttpClient() {
if (DEBUG) {
enableDebug();
}
// Create and initialize HTTP parameters
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// Create an HttpClient with the ThreadSafeClientConnManager.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
params, schemeRegistry);
mClient = new DefaultHttpClient(cm, params);
// Setup BasicAuth
BasicScheme basicScheme = new BasicScheme();
mAuthScope = new AuthScope(SERVER_HOST, AuthScope.ANY_PORT);
// mClient.setAuthSchemes(authRegistry);
mClient.setCredentialsProvider(new BasicCredentialsProvider());
// Generate BASIC scheme object and stick it to the local
// execution context
localcontext = new BasicHttpContext();
localcontext.setAttribute("preemptive-auth", basicScheme);
// first request interceptor
mClient.addRequestInterceptor(preemptiveAuth, 0);
// Support GZIP
mClient.addResponseInterceptor(gzipResponseIntercepter);
// TODO: need to release this connection in httpRequest()
// cm.releaseConnection(conn, validDuration, timeUnit);
// httpclient.getConnectionManager().shutdown();
}
/**
* HttpRequestInterceptor for DefaultHttpClient
*/
private static HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context) {
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(),
targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
private static HttpResponseInterceptor gzipResponseIntercepter = new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context)
throws org.apache.http.HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GzipDecompressingEntity(response
.getEntity()));
return;
}
}
}
}
};
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent() throws IOException,
IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
/**
* Setup Credentials for HTTP Basic Auth
*
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
mUserId = username;
mPassword = password;
mClient.getCredentialsProvider().setCredentials(mAuthScope,
new UsernamePasswordCredentials(username, password));
isAuthenticationEnabled = true;
}
public Response post(String url, ArrayList<BasicNameValuePair> postParams,
boolean authenticated) throws HttpException {
if (null == postParams) {
postParams = new ArrayList<BasicNameValuePair>();
}
return httpRequest(url, postParams, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpPost.METHOD_NAME);
}
public Response post(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url) throws HttpException {
return httpRequest(url, null, false, HttpPost.METHOD_NAME);
}
public Response post(String url, File file) throws HttpException {
return httpRequest(url, null, file, false, HttpPost.METHOD_NAME);
}
/**
* POST一个文件
*
* @param url
* @param file
* @param authenticate
* @return
* @throws HttpException
*/
public Response post(String url, File file, boolean authenticate)
throws HttpException {
return httpRequest(url, null, file, authenticate, HttpPost.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params,
boolean authenticated) throws HttpException {
return httpRequest(url, params, authenticated, HttpGet.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpGet.METHOD_NAME);
}
public Response get(String url) throws HttpException {
return httpRequest(url, null, false, HttpGet.METHOD_NAME);
}
public Response get(String url, boolean authenticated) throws HttpException {
return httpRequest(url, null, authenticated, HttpGet.METHOD_NAME);
}
public Response httpRequest(String url,
ArrayList<BasicNameValuePair> postParams, boolean authenticated,
String httpMethod) throws HttpException {
return httpRequest(url, postParams, null, authenticated, httpMethod);
}
/**
* Execute the DefaultHttpClient
*
* @param url
* target
* @param postParams
* @param file
* can be NULL
* @param authenticated
* need or not
* @param httpMethod
* HttpPost.METHOD_NAME HttpGet.METHOD_NAME
* HttpDelete.METHOD_NAME
* @return Response from server
* @throws HttpException
* 此异常包装了一系列底层异常 <br />
* <br />
* 1. 底层异常, 可使用getCause()查看: <br />
* <li>URISyntaxException, 由`new URI` 引发的.</li> <li>IOException,
* 由`createMultipartEntity` 或 `UrlEncodedFormEntity` 引发的.</li>
* <li>IOException和ClientProtocolException,
* 由`HttpClient.execute` 引发的.</li><br />
*
* 2. 当响应码不为200时报出的各种子类异常: <li>HttpRequestException,
* 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常, 首先检查request log,
* 确认不是人为错误导致请求失败</li> <li>HttpAuthException, 通常发生在Auth失败,
* 检查用于验证登录的用户名/密码/KEY等</li> <li>HttpRefusedException,
* 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因 服务器会返回拒绝理由,
* 调用HttpRefusedException#getError#getMessage查看</li> <li>
* HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li> <li>
* HttpException, 其他未知错误.</li>
*/
public Response httpRequest(String url,
ArrayList<BasicNameValuePair> postParams, File file,
boolean authenticated, String httpMethod) throws HttpException {
Log.d(TAG, "Sending " + httpMethod + " request to " + url);
if (Configuration.getDebug()) {
}
URI uri = createURI(url);
HttpResponse response = null;
Response res = null;
HttpUriRequest method = null;
// Create POST, GET or DELETE METHOD
method = createMethod(httpMethod, uri, file, postParams);
// Setup ConnectionParams, Request Headers
SetupHTTPConnectionParams(method);
// Execute Request
try {
response = mClient.execute(method, localcontext);
res = new Response(response);
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException(e.getMessage(), e);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
// It will throw a weiboException while status code is not 200
} else {
Log.e(TAG, "response is null");
}
if (Configuration.getDebug()) {
}
return res;
}
/**
* CreateURI from URL string
*
* @param url
* @return request URI
* @throws HttpException
* Cause by URISyntaxException
*/
private URI createURI(String url) throws HttpException {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException("Invalid URL.");
}
return uri;
}
/**
* 创建可带一个File的MultipartEntity
*
* @param filename
* 文件名
* @param file
* 文件
* @param postParams
* 其他POST参数
* @return 带文件和其他参数的Entity
* @throws UnsupportedEncodingException
*/
private MultipartEntity createMultipartEntity(String filename, File file,
ArrayList<BasicNameValuePair> postParams)
throws UnsupportedEncodingException {
MultipartEntity entity = new MultipartEntity();
// Don't try this. Server does not appear to support chunking.
// entity.addPart("media", new InputStreamBody(imageStream, "media"));
entity.addPart(filename, new FileBody(file));
if(postParams!=null){
for (BasicNameValuePair param : postParams) {
entity.addPart(param.getName(), new StringBody(param.getValue()));
}
}
return entity;
}
/**
* Setup HTTPConncetionParams
*
* @param method
*/
private void SetupHTTPConnectionParams(HttpUriRequest method) {
HttpConnectionParams.setConnectionTimeout(method.getParams(),
CONNECTION_TIMEOUT_MS);
HttpConnectionParams
.setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS);
mClient.setHttpRequestRetryHandler(requestRetryHandler);
method.addHeader("Accept-Encoding", "gzip, deflate");
method.addHeader("Accept-Charset", "UTF-8,*;q=0.5");
}
/**
* Create request method, such as POST, GET, DELETE
*
* @param httpMethod
* "GET","POST","DELETE"
* @param uri
* 请求的URI
* @param file
* 可为null
* @param postParams
* POST参数
* @return httpMethod Request implementations for the various HTTP methods
* like GET and POST.
* @throws HttpException
* createMultipartEntity 或 UrlEncodedFormEntity引发的IOException
*/
private HttpUriRequest createMethod(String httpMethod, URI uri, File file,
ArrayList<BasicNameValuePair> postParams) throws HttpException {
HttpUriRequest method;
if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
// POST METHOD
HttpPost post = new HttpPost(uri);
// See this:
// http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e178b1d3d63d8e3b
post.getParams().setBooleanParameter(
"http.protocol.expect-continue", false);
try {
HttpEntity entity = null;
if (null != file) {
entity = createMultipartEntity("f", file, postParams);
post.setEntity(entity);
} else if (null != postParams) {
entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);
}
post.setEntity(entity);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
method = post;
} else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
method = new HttpDelete(uri);
} else {
method = new HttpGet(uri);
}
return method;
}
/**
* 解析HTTP错误码
*
* @param statusCode
* @return
*/
private static String getCause(int statusCode) {
String cause = null;
switch (statusCode) {
case NOT_MODIFIED:
break;
case BAD_REQUEST:
cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting.";
break;
case NOT_AUTHORIZED:
cause = "Authentication credentials were missing or incorrect.";
break;
case FORBIDDEN:
cause = "The request is understood, but it has been refused. An accompanying error message will explain why.";
break;
case NOT_FOUND:
cause = "The URI requested is invalid or the resource requested, such as a user, does not exists.";
break;
case NOT_ACCEPTABLE:
cause = "Returned by the Search API when an invalid format is specified in the request.";
break;
case INTERNAL_SERVER_ERROR:
cause = "Something is broken. Please post to the group so the Weibo team can investigate.";
break;
case BAD_GATEWAY:
cause = "Weibo is down or being upgraded.";
break;
case SERVICE_UNAVAILABLE:
cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited.";
break;
default:
cause = "";
}
return statusCode + ":" + cause;
}
public boolean isAuthenticationEnabled() {
return isAuthenticationEnabled;
}
public static void log(String msg) {
if (DEBUG) {
Log.d(TAG, msg);
}
}
public static String encode(String value) throws HttpException {
try {
return URLEncoder.encode(value, HTTP.UTF_8);
} catch (UnsupportedEncodingException e_e) {
throw new HttpException(e_e.getMessage(), e_e);
}
}
public static String encodeParameters(ArrayList<BasicNameValuePair> params)
throws HttpException {
StringBuffer buf = new StringBuffer();
for (int j = 0; j < params.size(); j++) {
if (j != 0) {
buf.append("&");
}
try {
buf.append(URLEncoder.encode(params.get(j).getName(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(params.get(j).getValue(),
"UTF-8"));
} catch (java.io.UnsupportedEncodingException neverHappen) {
throw new HttpException(neverHappen.getMessage(), neverHappen);
}
}
return buf.toString();
}
/**
* 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复
*/
private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
// 自定义的恢复策略
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context) {
// 设置恢复策略,在发生异常时候将自动重试N次
if (executionCount >= RETRIED_TIME) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
if (!idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
/**
* 生成POST Parameters助手
*
* @param nameValuePair
* 参数(一个或多个)
* @return post parameters
*/
public ArrayList<BasicNameValuePair> createParams(
BasicNameValuePair... nameValuePair) {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (BasicNameValuePair param : nameValuePair) {
params.add(param);
}
return params;
}
}