PageRenderTime 59ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/yns/net/http/AsyncHttpClient.java

https://gitlab.com/huangjunbin/YNS
Java | 849 lines | 401 code | 70 blank | 378 comment | 49 complexity | 14c8149f771e2415a2c6f0062dc28de9 MD5 | raw file
  1. package com.yns.net.http;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.lang.ref.WeakReference;
  5. import java.util.HashMap;
  6. import java.util.LinkedList;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.WeakHashMap;
  10. import java.util.concurrent.ArrayBlockingQueue;
  11. import java.util.concurrent.Future;
  12. import java.util.concurrent.ThreadPoolExecutor;
  13. import java.util.concurrent.TimeUnit;
  14. import java.util.zip.GZIPInputStream;
  15. import org.apache.http.Header;
  16. import org.apache.http.HeaderElement;
  17. import org.apache.http.HttpEntity;
  18. import org.apache.http.HttpRequest;
  19. import org.apache.http.HttpRequestInterceptor;
  20. import org.apache.http.HttpResponse;
  21. import org.apache.http.HttpResponseInterceptor;
  22. import org.apache.http.HttpVersion;
  23. import org.apache.http.auth.AuthScope;
  24. import org.apache.http.auth.UsernamePasswordCredentials;
  25. import org.apache.http.client.CookieStore;
  26. import org.apache.http.client.HttpClient;
  27. import org.apache.http.client.methods.HttpDelete;
  28. import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
  29. import org.apache.http.client.methods.HttpGet;
  30. import org.apache.http.client.methods.HttpPost;
  31. import org.apache.http.client.methods.HttpPut;
  32. import org.apache.http.client.methods.HttpUriRequest;
  33. import org.apache.http.client.protocol.ClientContext;
  34. import org.apache.http.conn.params.ConnManagerParams;
  35. import org.apache.http.conn.params.ConnPerRouteBean;
  36. import org.apache.http.conn.scheme.PlainSocketFactory;
  37. import org.apache.http.conn.scheme.Scheme;
  38. import org.apache.http.conn.scheme.SchemeRegistry;
  39. import org.apache.http.conn.ssl.SSLSocketFactory;
  40. import org.apache.http.entity.HttpEntityWrapper;
  41. import org.apache.http.impl.client.DefaultHttpClient;
  42. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  43. import org.apache.http.message.BasicNameValuePair;
  44. import org.apache.http.params.BasicHttpParams;
  45. import org.apache.http.params.HttpConnectionParams;
  46. import org.apache.http.params.HttpParams;
  47. import org.apache.http.params.HttpProtocolParams;
  48. import org.apache.http.protocol.BasicHttpContext;
  49. import org.apache.http.protocol.HttpContext;
  50. import org.apache.http.protocol.SyncBasicHttpContext;
  51. import com.alibaba.fastjson.JSONObject;
  52. import android.content.Context;
  53. import android.util.Log;
  54. public class AsyncHttpClient {
  55. String ttag = "AsyncHttpClient";
  56. private static final String VERSION = "1.1";
  57. /** 线程池维护线程的最少数量 */
  58. private static final int DEFAULT_CORE_POOL_SIZE = 5;
  59. private static final int DEFAULT_MAXIMUM_POOL_SIZE = 10;
  60. /** 线程池维护线程所允许的空闲时间 */
  61. private static final int DEFAULT_KEEP_ALIVETIME = 0;
  62. /** http请求最大并发连接数 */
  63. private static final int DEFAULT_MAX_CONNECTIONS = 10;
  64. /** 超时时间,默认10秒 */
  65. private static final int DEFAULT_SOCKET_TIMEOUT = 10 * 1000;
  66. /** 默认错误尝试次数 */
  67. private static final int DEFAULT_MAX_RETRIES = 5;
  68. /** 默认的套接字缓冲区大小 */
  69. private static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192;
  70. private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
  71. private static final String ENCODING_GZIP = "gzip";
  72. private static int maxConnections = DEFAULT_MAX_CONNECTIONS;
  73. private static int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
  74. private final DefaultHttpClient httpClient;
  75. private final HttpContext httpContext;
  76. private ThreadPoolExecutor threadPool;
  77. private final Map<Context, List<WeakReference<Future<?>>>> requestMap;
  78. private final Map<String, String> clientHeaderMap;
  79. public AsyncHttpClient() {
  80. BasicHttpParams httpParams = new BasicHttpParams();
  81. ConnManagerParams.setTimeout(httpParams, socketTimeout);
  82. ConnManagerParams.setMaxConnectionsPerRoute(httpParams,
  83. new ConnPerRouteBean(maxConnections));
  84. ConnManagerParams.setMaxTotalConnections(httpParams,
  85. DEFAULT_MAX_CONNECTIONS);
  86. HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
  87. HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
  88. HttpConnectionParams.setTcpNoDelay(httpParams, true);
  89. HttpConnectionParams.setSocketBufferSize(httpParams,
  90. DEFAULT_SOCKET_BUFFER_SIZE);
  91. HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
  92. HttpProtocolParams.setUserAgent(httpParams, String.format(
  93. "thinkandroid/%s (http://www.thinkandroid.cn)", VERSION));
  94. SchemeRegistry schemeRegistry = new SchemeRegistry();
  95. schemeRegistry.register(new Scheme("http", PlainSocketFactory
  96. .getSocketFactory(), 80));
  97. schemeRegistry.register(new Scheme("https", SSLSocketFactory
  98. .getSocketFactory(), 443));
  99. ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
  100. httpParams, schemeRegistry);
  101. httpContext = new SyncBasicHttpContext(new BasicHttpContext());
  102. httpClient = new DefaultHttpClient(cm, httpParams);
  103. httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
  104. @Override
  105. public void process(HttpRequest request, HttpContext context) {
  106. if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
  107. request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
  108. }
  109. for (String header : clientHeaderMap.keySet()) {
  110. request.addHeader(header, clientHeaderMap.get(header));
  111. }
  112. }
  113. });
  114. httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
  115. @Override
  116. public void process(HttpResponse response, HttpContext context) {
  117. final HttpEntity entity = response.getEntity();
  118. if (entity == null) {
  119. return;
  120. }
  121. final Header encoding = entity.getContentEncoding();
  122. if (encoding != null) {
  123. for (HeaderElement element : encoding.getElements()) {
  124. if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
  125. response.setEntity(new InflatingEntity(response
  126. .getEntity()));
  127. break;
  128. }
  129. }
  130. }
  131. }
  132. });
  133. httpClient.setHttpRequestRetryHandler(new RetryHandler(
  134. DEFAULT_MAX_RETRIES));
  135. threadPool = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE,
  136. DEFAULT_MAXIMUM_POOL_SIZE, DEFAULT_KEEP_ALIVETIME,
  137. TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
  138. new ThreadPoolExecutor.CallerRunsPolicy());
  139. requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
  140. clientHeaderMap = new HashMap<String, String>();
  141. }
  142. /**
  143. * Get the underlying HttpClient instance. This is useful for setting
  144. * additional fine-grained settings for requests by accessing the client's
  145. * ConnectionManager, HttpParams and SchemeRegistry.
  146. */
  147. public HttpClient getHttpClient() {
  148. return this.httpClient;
  149. }
  150. /**
  151. * Get the underlying HttpContext instance. This is useful for getting and
  152. * setting fine-grained settings for requests by accessing the context's
  153. * attributes such as the CookieStore.
  154. */
  155. public HttpContext getHttpContext() {
  156. return this.httpContext;
  157. }
  158. /**
  159. * Sets an optional CookieStore to use when making requests
  160. *
  161. * @param cookieStore
  162. * The CookieStore implementation to use, usually an instance of
  163. * {@link PersistentCookieStore}
  164. */
  165. public void setCookieStore(CookieStore cookieStore) {
  166. httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
  167. }
  168. /**
  169. * Overrides the threadpool implementation used when queuing/pooling
  170. * requests. By default, Executors.newCachedThreadPool() is used.
  171. *
  172. * @param threadPool
  173. * an instance of {@link ThreadPoolExecutor} to use for
  174. * queuing/pooling requests.
  175. */
  176. public void setThreadPool(ThreadPoolExecutor threadPool) {
  177. this.threadPool = threadPool;
  178. }
  179. /**
  180. * Sets the User-Agent header to be sent with each request. By default,
  181. * "Android Asynchronous Http Client/VERSION (http://loopj.com/android-async-http/)"
  182. * is used.
  183. *
  184. * @param userAgent
  185. * the string to use in the User-Agent header.
  186. */
  187. public void setUserAgent(String userAgent) {
  188. HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
  189. }
  190. /**
  191. * Sets the connection time oout. By default, 10 seconds
  192. *
  193. * @param timeout
  194. * the connect/socket timeout in milliseconds
  195. */
  196. public void setTimeout(int timeout) {
  197. final HttpParams httpParams = this.httpClient.getParams();
  198. ConnManagerParams.setTimeout(httpParams, timeout);
  199. HttpConnectionParams.setSoTimeout(httpParams, timeout);
  200. HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
  201. }
  202. /**
  203. * Sets the SSLSocketFactory to user when making requests. By default, a
  204. * new, default SSLSocketFactory is used.
  205. *
  206. * @param sslSocketFactory
  207. * the socket factory to use for https requests.
  208. */
  209. public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
  210. this.httpClient.getConnectionManager().getSchemeRegistry()
  211. .register(new Scheme("https", sslSocketFactory, 443));
  212. }
  213. /**
  214. * Sets headers that will be added to all requests this client makes (before
  215. * sending).
  216. *
  217. * @param header
  218. * the name of the header
  219. * @param value
  220. * the contents of the header
  221. */
  222. public void addHeader(String header, String value) {
  223. clientHeaderMap.put(header, value);
  224. }
  225. /**
  226. * Sets basic authentication for the request. Uses AuthScope.ANY. This is
  227. * the same as setBasicAuth('username','password',AuthScope.ANY)
  228. *
  229. * @param username
  230. * @param password
  231. */
  232. public void setBasicAuth(String user, String pass) {
  233. AuthScope scope = AuthScope.ANY;
  234. setBasicAuth(user, pass, scope);
  235. }
  236. /**
  237. * Sets basic authentication for the request. You should pass in your
  238. * AuthScope for security. It should be like this
  239. * setBasicAuth("username","password", new
  240. * AuthScope("host",port,AuthScope.ANY_REALM))
  241. *
  242. * @param username
  243. * @param password
  244. * @param scope
  245. * - an AuthScope object
  246. *
  247. */
  248. public void setBasicAuth(String user, String pass, AuthScope scope) {
  249. UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
  250. user, pass);
  251. this.httpClient.getCredentialsProvider().setCredentials(scope,
  252. credentials);
  253. }
  254. /**
  255. * Cancels any pending (or potentially active) requests associated with the
  256. * passed Context.
  257. * <p>
  258. * <b>Note:</b> This will only affect requests which were created with a
  259. * non-null android Context. This method is intended to be used in the
  260. * onDestroy method of your android activities to destroy all requests which
  261. * are no longer required.
  262. *
  263. * @param context
  264. * the android Context instance associated to the request.
  265. * @param mayInterruptIfRunning
  266. * specifies if active requests should be cancelled along with
  267. * pending requests.
  268. */
  269. public void cancelRequests(Context context, boolean mayInterruptIfRunning) {
  270. List<WeakReference<Future<?>>> requestList = requestMap.get(context);
  271. if (requestList != null) {
  272. for (WeakReference<Future<?>> requestRef : requestList) {
  273. Future<?> request = requestRef.get();
  274. if (request != null) {
  275. request.cancel(mayInterruptIfRunning);
  276. }
  277. }
  278. }
  279. requestMap.remove(context);
  280. }
  281. //
  282. // HTTP GET Requests
  283. //
  284. /**
  285. * Perform a HTTP GET request, without any parameters.
  286. *
  287. * @param url
  288. * the URL to send the request to.
  289. * @param responseHandler
  290. * the response handler instance that should handle the response.
  291. */
  292. public void get(String url, AsyncHttpResponseHandler responseHandler) {
  293. get(null, url, null, responseHandler);
  294. }
  295. /**
  296. * Perform a HTTP GET request with parameters.
  297. *
  298. * @param url
  299. * the URL to send the request to.
  300. * @param params
  301. * additional GET parameters to send with the request.
  302. * @param responseHandler
  303. * the response handler instance that should handle the response.
  304. */
  305. public void get(String url, RequestParams params,
  306. AsyncHttpResponseHandler responseHandler) {
  307. get(null, url, params, responseHandler);
  308. }
  309. /**
  310. * Perform a HTTP GET request without any parameters and track the Android
  311. * Context which initiated the request.
  312. *
  313. * @param context
  314. * the Android Context which initiated the request.
  315. * @param url
  316. * the URL to send the request to.
  317. * @param responseHandler
  318. * the response handler instance that should handle the response.
  319. */
  320. public void get(Context context, String url,
  321. AsyncHttpResponseHandler responseHandler) {
  322. get(context, url, null, responseHandler);
  323. }
  324. /**
  325. * Perform a HTTP GET request and track the Android Context which initiated
  326. * the request.
  327. *
  328. * @param context
  329. * the Android Context which initiated the request.
  330. * @param url
  331. * the URL to send the request to.
  332. * @param params
  333. * additional GET parameters to send with the request.
  334. * @param responseHandler
  335. * the response handler instance that should handle the response.
  336. */
  337. public void get(Context context, String url, RequestParams params,
  338. AsyncHttpResponseHandler responseHandler) {
  339. sendRequest(httpClient, httpContext,
  340. new HttpGet(getUrlWithQueryString(url, params)), null,
  341. responseHandler, context);
  342. }
  343. //
  344. // HTTP download Requests
  345. //
  346. public void download(String url, AsyncHttpResponseHandler responseHandler) {
  347. download(null, url, null, responseHandler);
  348. }
  349. public void download(String url, RequestParams params,
  350. AsyncHttpResponseHandler responseHandler) {
  351. download(null, url, params, responseHandler);
  352. }
  353. /**
  354. * Perform a HTTP GET request without any parameters and track the Android
  355. * Context which initiated the request.
  356. *
  357. * @param context
  358. * the Android Context which initiated the request.
  359. * @param url
  360. * the URL to send the request to.
  361. * @param responseHandler
  362. * the response handler instance that should handle the response.
  363. */
  364. public void download(Context context, String url,
  365. AsyncHttpResponseHandler responseHandler) {
  366. download(context, url, null, responseHandler);
  367. }
  368. /**
  369. * Perform a HTTP GET request and track the Android Context which initiated
  370. * the request.
  371. *
  372. * @param context
  373. * the Android Context which initiated the request.
  374. * @param url
  375. * the URL to send the request to.
  376. * @param params
  377. * additional GET parameters to send with the request.
  378. * @param responseHandler
  379. * the response handler instance that should handle the response.
  380. */
  381. public void download(Context context, String url, RequestParams params,
  382. AsyncHttpResponseHandler responseHandler) {
  383. sendRequest(httpClient, httpContext,
  384. new HttpGet(getUrlWithQueryString(url, params)), null,
  385. responseHandler, context);
  386. }
  387. /**
  388. * Perform a HTTP GET request and track the Android Context which initiated
  389. * the request with customized headers
  390. *
  391. * @param url
  392. * the URL to send the request to.
  393. * @param headers
  394. * set headers only for this request
  395. * @param params
  396. * additional GET parameters to send with the request.
  397. * @param responseHandler
  398. * the response handler instance that should handle the response.
  399. */
  400. public void get(Context context, String url, Header[] headers,
  401. RequestParams params, AsyncHttpResponseHandler responseHandler) {
  402. HttpUriRequest request = new HttpGet(getUrlWithQueryString(url, params));
  403. if (headers != null)
  404. request.setHeaders(headers);
  405. sendRequest(httpClient, httpContext, request, null, responseHandler,
  406. context);
  407. }
  408. //
  409. // HTTP POST Requests
  410. //
  411. /**
  412. * Perform a HTTP POST request, without any parameters.
  413. *
  414. * @param url
  415. * the URL to send the request to.
  416. * @param responseHandler
  417. * the response handler instance that should handle the response.
  418. */
  419. public void post(String url, AsyncHttpResponseHandler responseHandler) {
  420. post(null, url, null, responseHandler);
  421. }
  422. /**
  423. * Perform a HTTP POST request with parameters.
  424. *
  425. * @param url
  426. * the URL to send the request to.
  427. * @param params
  428. * additional POST parameters or files to send with the request.
  429. * @param responseHandler
  430. * the response handler instance that should handle the response.
  431. */
  432. public void post(String url, RequestParams params,
  433. AsyncHttpResponseHandler responseHandler) {
  434. post(null, url, params, responseHandler);
  435. }
  436. public void postJsonParams(String url, RequestParams params,
  437. AsyncHttpResponseHandler responseHandler) {
  438. RequestParams newParams = new RequestParams();
  439. JSONObject jsonObject = new JSONObject();
  440. JSONObject jsonPage = new JSONObject();
  441. for (BasicNameValuePair param : params.getParamsList()) {
  442. System.out.println(param.getName());
  443. System.out.println(param.getValue());
  444. if (!"action".equals(param.getName())) {
  445. jsonObject.put(param.getName(), param.getValue());
  446. } else {
  447. newParams.put("action", param.getValue());
  448. }
  449. if ("pageindex".equals(param.getName())) {
  450. jsonPage.put(param.getName(), param.getValue());
  451. }
  452. if ("pagecount".equals(param.getName())) {
  453. jsonPage.put(param.getName(), param.getValue());
  454. }
  455. }
  456. Log.d("AsyncHttpClient", jsonObject.toString());
  457. newParams.fileParams = params.fileParams;
  458. newParams.put("param", jsonObject.toString());
  459. if (jsonPage.getString("pageindex") != null
  460. && jsonPage.getString("pagecount") != null) {
  461. newParams.put("page", jsonPage.toString());
  462. }
  463. Log.d(ttag, jsonObject.toString());
  464. Log.d(ttag, jsonPage.toString());
  465. Log.d(ttag, newParams.toString());
  466. System.out.println(jsonObject.toString());
  467. System.out.println(jsonPage.toString());
  468. post(null, url, newParams, responseHandler);
  469. }
  470. /**
  471. * Perform a HTTP POST request and track the Android Context which initiated
  472. * the request.
  473. *
  474. * @param context
  475. * the Android Context which initiated the request.
  476. * @param url
  477. * the URL to send the request to.
  478. * @param params
  479. * additional POST parameters or files to send with the request.
  480. * @param responseHandler
  481. * the response handler instance that should handle the response.
  482. */
  483. public void post(Context context, String url, RequestParams params,
  484. AsyncHttpResponseHandler responseHandler) {
  485. post(context, url, paramsToEntity(params), null, responseHandler);
  486. }
  487. /**
  488. * Perform a HTTP POST request and track the Android Context which initiated
  489. * the request.
  490. *
  491. * @param context
  492. * the Android Context which initiated the request.
  493. * @param url
  494. * the URL to send the request to.
  495. * @param entity
  496. * a raw {@link HttpEntity} to send with the request, for
  497. * example, use this to send string/json/xml payloads to a server
  498. * by passing a {@link org.apache.http.entity.StringEntity}.
  499. * @param contentType
  500. * the content type of the payload you are sending, for example
  501. * application/json if sending a json payload.
  502. * @param responseHandler
  503. * the response handler instance that should handle the response.
  504. */
  505. public void post(Context context, String url, HttpEntity entity,
  506. String contentType, AsyncHttpResponseHandler responseHandler) {
  507. sendRequest(httpClient, httpContext,
  508. addEntityToRequestBase(new HttpPost(url), entity), contentType,
  509. responseHandler, context);
  510. }
  511. /**
  512. * Perform a HTTP POST request and track the Android Context which initiated
  513. * the request. Set headers only for this request
  514. *
  515. * @param context
  516. * the Android Context which initiated the request.
  517. * @param url
  518. * the URL to send the request to.
  519. * @param headers
  520. * set headers only for this request
  521. * @param params
  522. * additional POST parameters to send with the request.
  523. * @param contentType
  524. * the content type of the payload you are sending, for example
  525. * application/json if sending a json payload.
  526. * @param responseHandler
  527. * the response handler instance that should handle the response.
  528. */
  529. public void post(Context context, String url, Header[] headers,
  530. RequestParams params, String contentType,
  531. AsyncHttpResponseHandler responseHandler) {
  532. HttpEntityEnclosingRequestBase request = new HttpPost(url);
  533. if (params != null)
  534. request.setEntity(paramsToEntity(params));
  535. if (headers != null)
  536. request.setHeaders(headers);
  537. sendRequest(httpClient, httpContext, request, contentType,
  538. responseHandler, context);
  539. }
  540. /**
  541. * Perform a HTTP POST request and track the Android Context which initiated
  542. * the request. Set headers only for this request
  543. *
  544. * @param context
  545. * the Android Context which initiated the request.
  546. * @param url
  547. * the URL to send the request to.
  548. * @param headers
  549. * set headers only for this request
  550. * @param entity
  551. * a raw {@link HttpEntity} to send with the request, for
  552. * example, use this to send string/json/xml payloads to a server
  553. * by passing a {@link org.apache.http.entity.StringEntity}.
  554. * @param contentType
  555. * the content type of the payload you are sending, for example
  556. * application/json if sending a json payload.
  557. * @param responseHandler
  558. * the response handler instance that should handle the response.
  559. */
  560. public void post(Context context, String url, Header[] headers,
  561. HttpEntity entity, String contentType,
  562. AsyncHttpResponseHandler responseHandler) {
  563. HttpEntityEnclosingRequestBase request = addEntityToRequestBase(
  564. new HttpPost(url), entity);
  565. if (headers != null)
  566. request.setHeaders(headers);
  567. sendRequest(httpClient, httpContext, request, contentType,
  568. responseHandler, context);
  569. }
  570. //
  571. // HTTP PUT Requests
  572. //
  573. /**
  574. * Perform a HTTP PUT request, without any parameters.
  575. *
  576. * @param url
  577. * the URL to send the request to.
  578. * @param responseHandler
  579. * the response handler instance that should handle the response.
  580. */
  581. public void put(String url, AsyncHttpResponseHandler responseHandler) {
  582. put(null, url, null, responseHandler);
  583. }
  584. /**
  585. * Perform a HTTP PUT request with parameters.
  586. *
  587. * @param url
  588. * the URL to send the request to.
  589. * @param params
  590. * additional PUT parameters or files to send with the request.
  591. * @param responseHandler
  592. * the response handler instance that should handle the response.
  593. */
  594. public void put(String url, RequestParams params,
  595. AsyncHttpResponseHandler responseHandler) {
  596. put(null, url, params, responseHandler);
  597. }
  598. /**
  599. * Perform a HTTP PUT request and track the Android Context which initiated
  600. * the request.
  601. *
  602. * @param context
  603. * the Android Context which initiated the request.
  604. * @param url
  605. * the URL to send the request to.
  606. * @param params
  607. * additional PUT parameters or files to send with the request.
  608. * @param responseHandler
  609. * the response handler instance that should handle the response.
  610. */
  611. public void put(Context context, String url, RequestParams params,
  612. AsyncHttpResponseHandler responseHandler) {
  613. put(context, url, paramsToEntity(params), null, responseHandler);
  614. }
  615. /**
  616. * Perform a HTTP PUT request and track the Android Context which initiated
  617. * the request. And set one-time headers for the request
  618. *
  619. * @param context
  620. * the Android Context which initiated the request.
  621. * @param url
  622. * the URL to send the request to.
  623. * @param entity
  624. * a raw {@link HttpEntity} to send with the request, for
  625. * example, use this to send string/json/xml payloads to a server
  626. * by passing a {@link org.apache.http.entity.StringEntity}.
  627. * @param contentType
  628. * the content type of the payload you are sending, for example
  629. * application/json if sending a json payload.
  630. * @param responseHandler
  631. * the response handler instance that should handle the response.
  632. */
  633. public void put(Context context, String url, HttpEntity entity,
  634. String contentType, AsyncHttpResponseHandler responseHandler) {
  635. sendRequest(httpClient, httpContext,
  636. addEntityToRequestBase(new HttpPut(url), entity), contentType,
  637. responseHandler, context);
  638. }
  639. /**
  640. * Perform a HTTP PUT request and track the Android Context which initiated
  641. * the request. And set one-time headers for the request
  642. *
  643. * @param context
  644. * the Android Context which initiated the request.
  645. * @param url
  646. * the URL to send the request to.
  647. * @param headers
  648. * set one-time headers for this request
  649. * @param entity
  650. * a raw {@link HttpEntity} to send with the request, for
  651. * example, use this to send string/json/xml payloads to a server
  652. * by passing a {@link org.apache.http.entity.StringEntity}.
  653. * @param contentType
  654. * the content type of the payload you are sending, for example
  655. * application/json if sending a json payload.
  656. * @param responseHandler
  657. * the response handler instance that should handle the response.
  658. */
  659. public void put(Context context, String url, Header[] headers,
  660. HttpEntity entity, String contentType,
  661. AsyncHttpResponseHandler responseHandler) {
  662. HttpEntityEnclosingRequestBase request = addEntityToRequestBase(
  663. new HttpPut(url), entity);
  664. if (headers != null)
  665. request.setHeaders(headers);
  666. sendRequest(httpClient, httpContext, request, contentType,
  667. responseHandler, context);
  668. }
  669. //
  670. // HTTP DELETE Requests
  671. //
  672. /**
  673. * Perform a HTTP DELETE request.
  674. *
  675. * @param url
  676. * the URL to send the request to.
  677. * @param responseHandler
  678. * the response handler instance that should handle the response.
  679. */
  680. public void delete(String url, AsyncHttpResponseHandler responseHandler) {
  681. delete(null, url, responseHandler);
  682. }
  683. /**
  684. * Perform a HTTP DELETE request.
  685. *
  686. * @param context
  687. * the Android Context which initiated the request.
  688. * @param url
  689. * the URL to send the request to.
  690. * @param responseHandler
  691. * the response handler instance that should handle the response.
  692. */
  693. public void delete(Context context, String url,
  694. AsyncHttpResponseHandler responseHandler) {
  695. final HttpDelete delete = new HttpDelete(url);
  696. sendRequest(httpClient, httpContext, delete, null, responseHandler,
  697. context);
  698. }
  699. /**
  700. * Perform a HTTP DELETE request.
  701. *
  702. * @param context
  703. * the Android Context which initiated the request.
  704. * @param url
  705. * the URL to send the request to.
  706. * @param headers
  707. * set one-time headers for this request
  708. * @param responseHandler
  709. * the response handler instance that should handle the response.
  710. */
  711. public void delete(Context context, String url, Header[] headers,
  712. AsyncHttpResponseHandler responseHandler) {
  713. final HttpDelete delete = new HttpDelete(url);
  714. if (headers != null)
  715. delete.setHeaders(headers);
  716. sendRequest(httpClient, httpContext, delete, null, responseHandler,
  717. context);
  718. }
  719. // Private stuff
  720. protected void sendRequest(DefaultHttpClient client,
  721. HttpContext httpContext, HttpUriRequest uriRequest,
  722. String contentType, AsyncHttpResponseHandler responseHandler,
  723. Context context) {
  724. if (contentType != null) {
  725. uriRequest.addHeader("Content-Type", contentType);
  726. }
  727. Future<?> request = threadPool.submit(new AsyncHttpRequest(client,
  728. httpContext, uriRequest, responseHandler));
  729. if (context != null) {
  730. // Add request to request map
  731. List<WeakReference<Future<?>>> requestList = requestMap
  732. .get(context);
  733. if (requestList == null) {
  734. requestList = new LinkedList<WeakReference<Future<?>>>();
  735. requestMap.put(context, requestList);
  736. }
  737. requestList.add(new WeakReference<Future<?>>(request));
  738. // TODO: Remove dead weakrefs from requestLists?
  739. }
  740. }
  741. public static String getUrlWithQueryString(String url, RequestParams params) {
  742. if (params != null) {
  743. String paramString = params.getParamString();
  744. if (url.indexOf("?") == -1) {
  745. url += "?" + paramString;
  746. } else {
  747. url += "&" + paramString;
  748. }
  749. }
  750. return url;
  751. }
  752. private HttpEntity paramsToEntity(RequestParams params) {
  753. HttpEntity entity = null;
  754. if (params != null) {
  755. entity = params.getEntity();
  756. }
  757. return entity;
  758. }
  759. private HttpEntityEnclosingRequestBase addEntityToRequestBase(
  760. HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) {
  761. if (entity != null) {
  762. requestBase.setEntity(entity);
  763. }
  764. return requestBase;
  765. }
  766. private static class InflatingEntity extends HttpEntityWrapper {
  767. public InflatingEntity(HttpEntity wrapped) {
  768. super(wrapped);
  769. }
  770. @Override
  771. public InputStream getContent() throws IOException {
  772. return new GZIPInputStream(wrappedEntity.getContent());
  773. }
  774. @Override
  775. public long getContentLength() {
  776. return -1;
  777. }
  778. }
  779. }