1. 程式人生 > >安卓AsyncHttpClient網路開源框架

安卓AsyncHttpClient網路開源框架

Overview

An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing. You can also use it in Service or background thread, library will automatically recognize in which context is ran.

Features

  • Make asynchronous HTTP requests, handle responses in anonymous callbacks
  • HTTP requests happen outside the UI thread
  • Requests use a threadpool to cap concurrent resource usage
  • GET/POST params builder (RequestParams)
  • Multipart file uploads with no additional third party libraries
  • Streamed JSON uploads
     with no additional libraries
  • Handling circular and relative redirects
  • Tiny size overhead to your application, only 90kb for everything
  • Automatic smart request retries optimized for spotty mobile connections
  • Automatic gzip response decoding support for super-fast requests
  • Binary protocol communication with BinaryHttpResponseHandler
  • Built-in response parsing into JSON with JsonHttpResponseHandler
  • Saving response directly into file with FileAsyncHttpResponseHandler
  • Persistent cookie store, saves cookies into your app’s SharedPreferences
  • Integration with Jackson JSON, Gson or other JSON (de)serializing libraries withBaseJsonHttpResponseHandler
  • Support for SAX parser with SaxAsyncHttpResponseHandler
  • Support for languages and content encodings, not just UTF-8

Used in Production By Top Apps and Developers

Instagram is the #1 photo app on android, with over 10million users
Popular online pinboard. Organize and share things you love.
#1 first person shooting game on Android, by Glu Games.
Social game discovery app with millions of users
Pose
Pose is the #1 fashion app for sharing and discovering new styles
Async HTTP is used in production by thousands of top apps.

Installation & Basic Usage

Add maven dependency using Gradle buildscript in format

dependencies {
  compile 'com.loopj.android:android-async-http:1.4.5'
}

Import the http package.

import com.loopj.android.http.*;

Create a new AsyncHttpClient instance and make a request:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {

    @Override
    public void onStart() {
        // called before request is started
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // called when response HTTP status is "200 OK"
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
    }

    @Override
    public void onRetry(int retryNo) {
        // called when request is retried
	}
});

In this example, we’ll make a http client class with static accessors to make it easy to communicate with Twitter’s API.

import com.loopj.android.http.*;

public class TwitterRestClient {
  private static final String BASE_URL = "http://api.twitter.com/1/";

  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

This then makes it very easy to work with the Twitter API in your code:

import org.json.*;
import com.loopj.android.http.*;

class TwitterRestClientUsage {
    public void getPublicTimeline() throws JSONException {
        TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                // If the response is JSONObject instead of expected JSONArray
            }
            
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
                // Pull out the first event on the public timeline
                JSONObject firstEvent = timeline.get(0);
                String tweetText = firstEvent.getString("text");

                // Do something with the response
                System.out.println(tweetText);
            }
        });
    }
}

This library also includes a PersistentCookieStore which is an implementation of the Apache HttpClient CookieStore interface that automatically saves cookies to SharedPreferences storage on the Android device.

This is extremely useful if you want to use cookies to manage authentication sessions, since the user will remain logged in even after closing and re-opening your app.

First, create an instance of AsyncHttpClient:

AsyncHttpClient myClient = new AsyncHttpClient();

Now set this client’s cookie store to be a new instance of PersistentCookieStore, constructed with an activity or application context (usually this will suffice):

PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);

Any cookies received from servers will now be stored in the persistent cookie store.

To add your own cookies to the store, simply construct a new cookie and call addCookie:

BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);

Adding GET/POST Parameters with RequestParams

The RequestParams class is used to add optional GET or POST parameters to your requests.RequestParams can be built and constructed in various ways:

Create empty RequestParams and immediately add some parameters:

RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");

Create RequestParams for a single parameter:

RequestParams params = new RequestParams("single", "value");

Create RequestParams from an existing Map of key/value strings:

HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("key", "value");
RequestParams params = new RequestParams(paramMap);

Uploading Files with RequestParams

The RequestParams class additionally supports multipart file uploads as follows:

Add an InputStream to the RequestParams to upload:

InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");

Add a File object to the RequestParams to upload:

相關推薦

AsyncHttpClient網路開源框架

Overview An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your ap

10大開源框架

1. RxJava 2016 年 Android 界最火的莫過於 RxJava 了,如果你還不知道 RxJava,你所在公司,或者你所在的專案還沒有使用 RxJava,那真的是有點 out 了,RxJava 不僅大大簡化了程式碼,甚至可以說改變了我們的開發方式。 RxJava 是一種函式式、響應式的

Android-Fk:[開源框架] 崩潰資訊收集框架ACRA原理流程

Android-Fk:[開源框架] 安卓崩潰資訊收集框架ACRA原理流程 本文主要梳理ACRA原理及程式碼流程 順序圖的uml檔案 簡化圖的draw.io原始檔 分享至百度網盤 https://pan.baidu.com/s/1zAapEu9mmOZsTMDlCRCRQg 一. 學習

深入淺出熱門網路框架 OkHttp3 和 Retrofit 原理

OkHttp3 是目前安卓開發者使用率較高的基礎網路框架,Retrofit 則是在它的基礎上進行了更友好的封裝。熟悉它倆的原始碼和流程不僅可以方便我們在專案中定製,還可以提升我們的基礎架構能力,此外在面試中如果你可以對 OkHttp 的原始碼娓娓道來,同時能對 Retrofi

USB攝像頭 開源庫 UVCCamera 教程

相關 () 通用 texture weak 接口 type conn listen https://github.com/saki4510t/UVCCamera UVCCamera 聽名字就知道使用UVC( USB VEDIO CLASS) 協議的通用類庫。linux原生支

移動端和 IOS 開發框架 Framework7 布局

plus size ont open active image style ner 彈出 對應的各種效果,Framework7 裏面實現的方式比較多,這裏我就只寫我用的一種,樣式有的自己修改了的,想看官方詳細的參見 http://framework7.cn 一、手風琴布局A

實用優秀開源專案

沉浸式狀態列和沉浸式導航欄 參考資料:https://www.jianshu.com/p/2a884e211a62 開源地址 安卓常用工具類 參考資料: https://blankj.com/2016/07/31/android-utils-code/ 開源地址 動態許可

4g網路下訪問特別慢 APN為ipv4的時候可以訪問IPV6不可以訪問

經過對比發現,TCP3次握手的過程沒有問題,不是重發導致的!但是在3次握手前停滯了16s,這很奇怪!不經想問,3次握手前做了什麼!由於個人水平有限,猜測是不是域名解析的問題呢!和後臺交流一下!發現公司線上伺服器有2種解析方式,分別是ipv4和ipv6,最後只保留ipv4。 查資料看到原來android 預設

崩潰資訊收集框架ACRA

版權宣告:本文為博主高遠原創文章,轉載請註明出處:http://blog.csdn.net/wgyscsf    https://blog.csdn.net/wgyscsf/article/details/54314899 簡介 ACRA is a library

開發網路相關bug解決方案

兩個bug: 1: android.os.NetworkOnMainThreadException 原因:因為main執行緒要處理UI,預設不能使用網路導致假死 Android這個設計是為了防止網路請求時間過長而導致介面假死的情況發生。解決方案有兩個,一個是使用StrictMode,二是使用

獲取網路視訊的縮圖

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private Bitmap createVideoThumbnail(String url, int width, int height) { B

判斷網路

封裝好的  可以在後臺開啟一個service持續檢測處於什麼網路 public class NetUtil { //沒有網路 private static final int NETW

一個簡潔而不簡單的上下拉重新整理框架

首先先看一下效果圖吧== 重新整理動畫都很熟悉吧…so 本專案並不是重新整理控制元件,而是一個框架,定義了一個標準,可以整合實現自己想要的效果! 原始碼地址:https://github.com/tohodog/QSRefreshLayout 框

中多媒體vitamio框架的使用

Google公司開發安卓的時候,自帶的視訊媒體播放的api有很多限制,首先很多格式都是不支援的,但是現在我們國人一下科技自主開發了一種SDK來讓多媒體程式設計更加的簡單,雖然也是基於網上開源框架,但是我們可以直接使用,這個就是vitamio框架。首先感謝國人的辛苦和分享,支

手機安裝Xposed框架

     Xposed框架是一款可以在不修改APK的情況下影響程式執行(修改系統)的框架服務,基於它可以製作出許多功能強大的模組,且在功能不衝突的情況下同時運作。成功安裝外掛實現微信,QQ防撤回,搶紅

微信小程式之wx.request:fail錯誤,真機預覽請求無效問題解決,,ios網路預覽異常

問題描述:域名已經備案,我全部都有,也在後臺配置了,但是手機預覽,還是請求失敗, PC端是可以請求資料出來的 新版開發者工具增加了https檢查功能;可使用此功能直接檢查排查ssl協議版本問題:可能原因:0:後臺域名沒有配置0.1:域名不支援https1:沒有重啟工具;2:

關於通過網路介面解析Json資料的簡單實現

1 MainActivity.javapackage com.example.ms18.finalexam_2_20150861213;import android.os.Bundle;import android.os.Handler;import android.os.M

專案實戰之強大的網路請求框架okGo使用詳解(六):擴充套件專案okServer,更強大的下載上傳功能,支援斷點和多工管理

OkGo與OkDownload的區別就是,OkGo只是簡單的做一個下載功能,不具備斷點下載,暫停等操作,但是這在很多時候已經能滿足需要了。 而有些app需要有一個下載列表的功能,就像迅雷下載一樣,每個下載任務可以暫停,可以繼續,可以重新下載,可以有下載優先順序,這時候OkDownload就有

專案實戰之強大的網路請求框架okGo使用詳解(五):擴充套件專案okRx,完美結合RxJava

前言 在第一篇講解okGo框架新增依賴支援時,還記得我們額外新增的兩個依賴嗎,一個okRx和一個okServer,這兩個均是基於okGo框架的擴充套件專案,其中okRx可以使請求結合RxJava一起使用,而okServer則提供了強大的下載上傳功能,如斷點支援,多工管理等,本篇我們主要講

專案實戰之強大的網路請求框架okGo使用詳解(四):Cookie的管理

Cookie概念相關 具體來說cookie機制採用的是在客戶端保持狀態的方案,而session機制採用的是在伺服器端保持狀態的方案。同時我們也看到,由於採用伺服器端保持狀態的方案在客戶端也需要儲存一個標識,所以session機制是需要藉助於cookie機制來達到儲存標識的目的,所謂ses