/
AsyncHttpResponseHandler.java
executable file
·516 lines (459 loc) · 18.6 KB
/
AsyncHttpResponseHandler.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
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
https://github.com/android-async-http/android-async-http
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.loopj.android.http;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.util.Locale;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.StatusLine;
import cz.msebera.android.httpclient.client.HttpResponseException;
import cz.msebera.android.httpclient.util.ByteArrayBuffer;
/**
* Used to intercept and handle the responses from requests made using {@link AsyncHttpClient}. The
* {@link #onSuccess(int, cz.msebera.android.httpclient.Header[], byte[])} method is designed to be anonymously
* overridden with your own response handling code. <p> </p> Additionally, you can override the
* {@link #onFailure(int, cz.msebera.android.httpclient.Header[], byte[], Throwable)}, {@link #onStart()}, {@link
* #onFinish()}, {@link #onRetry(int)} and {@link #onProgress(long, long)} methods as required.
* <p> </p> For example: <p> </p>
* <pre>
* AsyncHttpClient client = new AsyncHttpClient();
* client.get("https://www.google.com", new AsyncHttpResponseHandler() {
* @Override
* public void onStart() {
* // Initiated the request
* }
*
* @Override
* public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
* // Successfully got a response
* }
*
* @Override
* public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable
* error)
* {
* // Response failed :(
* }
*
* @Override
* public void onRetry(int retryNo) {
* // Request was retried
* }
*
* @Override
* public void onProgress(long bytesWritten, long totalSize) {
* // Progress notification
* }
*
* @Override
* public void onFinish() {
* // Completed the request (either success or failure)
* }
* });
* </pre>
*/
@SuppressWarnings("DesignForExtension")
public abstract class AsyncHttpResponseHandler implements ResponseHandlerInterface {
public static final String DEFAULT_CHARSET = "UTF-8";
public static final String UTF8_BOM = "\uFEFF";
protected static final int SUCCESS_MESSAGE = 0;
protected static final int FAILURE_MESSAGE = 1;
protected static final int START_MESSAGE = 2;
protected static final int FINISH_MESSAGE = 3;
protected static final int PROGRESS_MESSAGE = 4;
protected static final int RETRY_MESSAGE = 5;
protected static final int CANCEL_MESSAGE = 6;
protected static final int BUFFER_SIZE = 4096;
private static final String LOG_TAG = "AsyncHttpRH";
private String responseCharset = DEFAULT_CHARSET;
private Handler handler;
private boolean useSynchronousMode;
private boolean usePoolThread;
private URI requestURI = null;
private Header[] requestHeaders = null;
private Looper looper = null;
private WeakReference<Object> TAG = new WeakReference<Object>(null);
/**
* Creates a new AsyncHttpResponseHandler
*/
public AsyncHttpResponseHandler() {
this(null);
}
/**
* Creates a new AsyncHttpResponseHandler with a user-supplied looper. If
* the passed looper is null, the looper attached to the current thread will
* be used.
*
* @param looper The looper to work with
*/
public AsyncHttpResponseHandler(Looper looper) {
// Do not use the pool's thread to fire callbacks by default.
this(looper == null ? Looper.myLooper() : looper, false);
}
/**
* Creates a new AsyncHttpResponseHandler and decide whether the callbacks
* will be fired on current thread's looper or the pool thread's.
*
* @param usePoolThread Whether to use the pool's thread to fire callbacks
*/
public AsyncHttpResponseHandler(boolean usePoolThread) {
this(usePoolThread ? null : Looper.myLooper(), usePoolThread);
}
private AsyncHttpResponseHandler(Looper looper, boolean usePoolThread) {
if (!usePoolThread) {
Utils.asserts(looper != null, "use looper thread, must call Looper.prepare() first!");
this.looper = looper;
// Create a handler on current thread to submit tasks
this.handler = new ResponderHandler(this, looper);
} else {
Utils.asserts(looper == null, "use pool thread, looper should be null!");
// If pool thread is to be used, there's no point in keeping a reference
// to the looper and handler.
this.looper = null;
this.handler = null;
}
this.usePoolThread = usePoolThread;
}
@Override
public Object getTag() {
return this.TAG.get();
}
@Override
public void setTag(Object TAG) {
this.TAG = new WeakReference<Object>(TAG);
}
@Override
public URI getRequestURI() {
return this.requestURI;
}
@Override
public void setRequestURI(URI requestURI) {
this.requestURI = requestURI;
}
@Override
public Header[] getRequestHeaders() {
return this.requestHeaders;
}
@Override
public void setRequestHeaders(Header[] requestHeaders) {
this.requestHeaders = requestHeaders;
}
@Override
public boolean getUseSynchronousMode() {
return useSynchronousMode;
}
@Override
public void setUseSynchronousMode(boolean sync) {
// A looper must be prepared before setting asynchronous mode.
if (!sync && looper == null) {
sync = true;
AsyncHttpClient.log.w(LOG_TAG, "Current thread has not called Looper.prepare(). Forcing synchronous mode.");
}
// If using asynchronous mode.
if (!sync && handler == null) {
// Create a handler on current thread to submit tasks
handler = new ResponderHandler(this, looper);
} else if (sync && handler != null) {
// TODO: Consider adding a flag to remove all queued messages.
handler = null;
}
useSynchronousMode = sync;
}
@Override
public boolean getUsePoolThread() {
return usePoolThread;
}
@Override
public void setUsePoolThread(boolean pool) {
// If pool thread is to be used, there's no point in keeping a reference
// to the looper and no need for a handler.
if (pool) {
looper = null;
handler = null;
}
usePoolThread = pool;
}
public String getCharset() {
return this.responseCharset == null ? DEFAULT_CHARSET : this.responseCharset;
}
/**
* Sets the charset for the response string. If not set, the default is UTF-8.
*
* @param charset to be used for the response string.
* @see <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html">Charset</a>
*/
public void setCharset(final String charset) {
this.responseCharset = charset;
}
/**
* Fired when the request progress, override to handle in your own code
*
* @param bytesWritten offset from start of file
* @param totalSize total size of file
*/
public void onProgress(long bytesWritten, long totalSize) {
AsyncHttpClient.log.v(LOG_TAG, String.format(Locale.US, "Progress %d from %d (%2.0f%%)", bytesWritten, totalSize, (totalSize > 0) ? (bytesWritten * 1.0 / totalSize) * 100 : -1));
}
/**
* Fired when the request is started, override to handle in your own code
*/
public void onStart() {
// default log warning is not necessary, because this method is just optional notification
}
/**
* Fired in all cases when the request is finished, after both success and failure, override to
* handle in your own code
*/
public void onFinish() {
// default log warning is not necessary, because this method is just optional notification
}
@Override
public void onPreProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
// default action is to do nothing...
}
@Override
public void onPostProcessResponse(ResponseHandlerInterface instance, HttpResponse response) {
// default action is to do nothing...
}
/**
* Fired when a request returns successfully, override to handle in your own code
*
* @param statusCode the status code of the response
* @param headers return headers, if any
* @param responseBody the body of the HTTP response from the server
*/
public abstract void onSuccess(int statusCode, Header[] headers, byte[] responseBody);
/**
* Fired when a request fails to complete, override to handle in your own code
*
* @param statusCode return HTTP status code
* @param headers return headers, if any
* @param responseBody the response body, if any
* @param error the underlying cause of the failure
*/
public abstract void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error);
/**
* Fired when a retry occurs, override to handle in your own code
*
* @param retryNo number of retry
*/
public void onRetry(int retryNo) {
AsyncHttpClient.log.d(LOG_TAG, String.format(Locale.US, "Request retry no. %d", retryNo));
}
public void onCancel() {
AsyncHttpClient.log.d(LOG_TAG, "Request got cancelled");
}
public void onUserException(Throwable error) {
AsyncHttpClient.log.e(LOG_TAG, "User-space exception detected!", error);
throw new RuntimeException(error);
}
@Override
final public void sendProgressMessage(long bytesWritten, long bytesTotal) {
sendMessage(obtainMessage(PROGRESS_MESSAGE, new Object[]{bytesWritten, bytesTotal}));
}
@Override
final public void sendSuccessMessage(int statusCode, Header[] headers, byte[] responseBytes) {
sendMessage(obtainMessage(SUCCESS_MESSAGE, new Object[]{statusCode, headers, responseBytes}));
}
@Override
final public void sendFailureMessage(int statusCode, Header[] headers, byte[] responseBody, Throwable throwable) {
sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[]{statusCode, headers, responseBody, throwable}));
}
@Override
final public void sendStartMessage() {
sendMessage(obtainMessage(START_MESSAGE, null));
}
@Override
final public void sendFinishMessage() {
sendMessage(obtainMessage(FINISH_MESSAGE, null));
}
@Override
final public void sendRetryMessage(int retryNo) {
sendMessage(obtainMessage(RETRY_MESSAGE, new Object[]{retryNo}));
}
@Override
final public void sendCancelMessage() {
sendMessage(obtainMessage(CANCEL_MESSAGE, null));
}
// Methods which emulate android's Handler and Message methods
protected void handleMessage(Message message) {
Object[] response;
try {
switch (message.what) {
case SUCCESS_MESSAGE:
response = (Object[]) message.obj;
if (response != null && response.length >= 3) {
onSuccess((Integer) response[0], (Header[]) response[1], (byte[]) response[2]);
} else {
AsyncHttpClient.log.e(LOG_TAG, "SUCCESS_MESSAGE didn't got enough params");
}
break;
case FAILURE_MESSAGE:
response = (Object[]) message.obj;
if (response != null && response.length >= 4) {
onFailure((Integer) response[0], (Header[]) response[1], (byte[]) response[2], (Throwable) response[3]);
} else {
AsyncHttpClient.log.e(LOG_TAG, "FAILURE_MESSAGE didn't got enough params");
}
break;
case START_MESSAGE:
onStart();
break;
case FINISH_MESSAGE:
onFinish();
break;
case PROGRESS_MESSAGE:
response = (Object[]) message.obj;
if (response != null && response.length >= 2) {
try {
onProgress((Long) response[0], (Long) response[1]);
} catch (Throwable t) {
AsyncHttpClient.log.e(LOG_TAG, "custom onProgress contains an error", t);
}
} else {
AsyncHttpClient.log.e(LOG_TAG, "PROGRESS_MESSAGE didn't got enough params");
}
break;
case RETRY_MESSAGE:
response = (Object[]) message.obj;
if (response != null && response.length == 1) {
onRetry((Integer) response[0]);
} else {
AsyncHttpClient.log.e(LOG_TAG, "RETRY_MESSAGE didn't get enough params");
}
break;
case CANCEL_MESSAGE:
onCancel();
break;
}
} catch (Throwable error) {
onUserException(error);
}
}
protected void sendMessage(Message msg) {
if (getUseSynchronousMode() || handler == null) {
handleMessage(msg);
} else if (!Thread.currentThread().isInterrupted()) { // do not send messages if request has been cancelled
Utils.asserts(handler != null, "handler should not be null!");
handler.sendMessage(msg);
}
}
/**
* Helper method to send runnable into local handler loop
*
* @param runnable runnable instance, can be null
*/
protected void postRunnable(Runnable runnable) {
if (runnable != null) {
if (getUseSynchronousMode() || handler == null) {
// This response handler is synchronous, run on current thread
runnable.run();
} else {
// Otherwise, run on provided handler
handler.post(runnable);
}
}
}
/**
* Helper method to create Message instance from handler
*
* @param responseMessageId constant to identify Handler message
* @param responseMessageData object to be passed to message receiver
* @return Message instance, should not be null
*/
protected Message obtainMessage(int responseMessageId, Object responseMessageData) {
return Message.obtain(handler, responseMessageId, responseMessageData);
}
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
// do not process if request has been cancelled
if (!Thread.currentThread().isInterrupted()) {
StatusLine status = response.getStatusLine();
byte[] responseBody;
responseBody = getResponseData(response.getEntity());
// additional cancellation check as getResponseData() can take non-zero time to process
if (!Thread.currentThread().isInterrupted()) {
if (status.getStatusCode() >= 300) {
sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
} else {
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
}
}
}
}
/**
* Returns byte array of response HttpEntity contents
*
* @param entity can be null
* @return response entity body or null
* @throws java.io.IOException if reading entity or creating byte array failed
*/
byte[] getResponseData(HttpEntity entity) throws IOException {
byte[] responseBody = null;
if (entity != null) {
InputStream instream = entity.getContent();
if (instream != null) {
long contentLength = entity.getContentLength();
if (contentLength > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int buffersize = (contentLength <= 0) ? BUFFER_SIZE : (int) contentLength;
try {
ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize);
try {
byte[] tmp = new byte[BUFFER_SIZE];
long count = 0;
int l;
// do not send messages if request has been cancelled
while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
count += l;
buffer.append(tmp, 0, l);
sendProgressMessage(count, (contentLength <= 0 ? 1 : contentLength));
}
} finally {
AsyncHttpClient.silentCloseInputStream(instream);
AsyncHttpClient.endEntityViaReflection(entity);
}
responseBody = buffer.toByteArray();
} catch (OutOfMemoryError e) {
System.gc();
throw new IOException("File too large to fit into available memory");
}
}
}
return responseBody;
}
/**
* Avoid leaks by using a non-anonymous handler class.
*/
private static class ResponderHandler extends Handler {
private final AsyncHttpResponseHandler mResponder;
ResponderHandler(AsyncHttpResponseHandler mResponder, Looper looper) {
super(looper);
this.mResponder = mResponder;
}
@Override
public void handleMessage(Message msg) {
mResponder.handleMessage(msg);
}
}
}