標籤:android style blog http io color os ar 使用
android-async-http開源網路架構是專門針對Android在Apache的基礎上構建的非同步且基於回調的http client。所有的請求全在UI線程之外發生,而callback發生在建立它的線程中,應用了Android的Handler發送訊息機制。
android-async-http的特點:(這段摘自網路)
- Make asynchronous HTTP requests, handle responses in anonymous callbacks
- 進行非同步HTTP請求,處理響應在匿名回調中完成
- HTTP requests happen outside the UI thread
- HTTP請求發生在UI線程之外
- Requests use a threadpool to cap concurrent resource usage
- 請求使用threadpool,限制並發資源使用方式
- GET/POST params builder (RequestParams)
- GET / POST參數構建使用(RequestParams)
- Multipart file uploads with no additional third party libraries
- Multipart 檔案上傳,沒有額外的第三方庫
- Tiny size overhead to your application, only 25kb for everything
- 在你的應用程式上利用很小的開銷,僅僅25 kb就可以做一切
- Automatic smart request retries optimized for spotty mobile connections
- 自動智能請求重試,最佳化了品質不一的移動串連
- Automatic gzip response decoding support for super-fast requests
- 自動解碼支援gzip反應速度超快的請求
- Binary file (images etc) downloading with BinaryHttpResponseHandler
- 二進位檔案(圖片等)的下載,使用BinaryHttpResponseHandler
- Built-in response parsing into JSON with JsonHttpResponseHandler
- 內建響應解析成JSON,使用JsonHttpResponseHandler
- Persistent cookie store, saves cookies into your app’s SharedPreferences
- 持久化cookie儲存,儲存cookie到你的應用程式的SharedPreferences
android-async-http開源庫:https://github.com/loopj/android-async-http
基本用法:
將下載好的的android-async-http開源庫壓縮包解壓,開啟檔案夾如所示:
開啟"releases"檔案夾,裡面後各個版本的jar包。
接著建立一個Android工程,取名為"zhj_async_http"。將1.4.5版本的jar包匯入並添加到工程中,
接下來就是敲代碼了。
先來一個最簡單的用法(請求百度頁面):
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.baidu.com", new TextHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, String response) { System.out.println(response); } @Override public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) { Log.d("ERROR", error); } });
整個步驟如下:
1、建立一個AsyncHttpClient對象。
2、用這個對象佈建要求方式(包括get、put、post、head、delete)。
3、傳入參數(包括請求地址、參數的設定、並指定一個ResponseHandlerInterface的執行個體接收請求結果)。
4、在onSuccess()方法中執行請求成功的操作,在onFailure()方法中執行請求失敗的操作。
怎麼樣?是不是感覺很簡單?
不過官方建議使用靜態方式,官方Demo:
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; }}View 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); } }); }}View Code
那麼,現在來使用android-async-http開源架構來實現擷取String字串、Json格式的資料和網狀圖片。
首先根據官方建議使用static實現一個HttpUtil.java(目前只使用get請求方式):
public class HttpUtil { private static AsyncHttpClient client = new AsyncHttpClient(); // 執行個體話對象 static { client.setTimeout(11000); // 設定連結逾時,如果不設定,預設為10s } public static AsyncHttpClient getClient() { return client; } public static void get(String urlString, AsyncHttpResponseHandler res) // 用一個完整url擷取一個string對象 { client.get(urlString, res); } public static void get(String urlString, RequestParams params, AsyncHttpResponseHandler res) // url裡面帶參數 { client.get(urlString, params, res); } public static void get(String urlString, JsonHttpResponseHandler res) // 不帶參數,擷取json對象或者數組 { client.get(urlString, res); } public static void get(String urlString, RequestParams params, JsonHttpResponseHandler res) // 帶參數,擷取json對象或者數組 { client.get(urlString, params, res); } public static void get(String uString, BinaryHttpResponseHandler bHandler) // 下載資料使用,會返回byte資料 { client.get(uString, bHandler); }}
布局檔案的實現:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/iv" android:layout_width="300dp" android:layout_height="300dp" /> <ScrollView android:id="@+id/sl" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" /> </ScrollView></LinearLayout>
接下來是MainActivity.java(三個方法分別是實現擷取Json(包括JSONObject和JSONArray)、String、網狀圖像)
public class MainActivity extends Activity { private TextView tv; private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); iv = (ImageView) findViewById(R.id.iv); Json(); String(); image(); } private void image() { AsyncHttpClient client = new AsyncHttpClient(); client.get( "http://b.hiphotos.baidu.com/zhidao/pic/item/d833c895d143ad4b08c2629580025aafa50f06f2.jpg", new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if (statusCode == 200) { BitmapFactory factory = new BitmapFactory(); Bitmap bitmap = factory.decodeByteArray( responseBody, 0, responseBody.length); iv.setImageBitmap(bitmap); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { error.printStackTrace(); } }); } private void String() { HttpUtil.get("http://www.baidu.com", new TextHttpResponseHandler() { @Override public void onSuccess(int arg0, Header[] arg1, String arg2) { tv.setText(arg2); } @Override public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) { tv.setText("請求百度失敗"); } }); } private void Json() { HttpUtil.get("http://m.weather.com.cn/data/101010100.html", new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { // TODO Auto-generated method stub super.onSuccess(statusCode, headers, response); if (statusCode == 200) { try { String str = response.getJSONObject( "weatherinfo").getString("index_d"); tv.setText(str); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { tv.setText("statusCode != 200"); } } }); }}
運行結果如:
(左圖是網狀圖像加String,右圖是網狀圖像加Json資料)
參考部落格:http://www.open-open.com/lib/view/open1369637365753.html
相關部落格:http://www.cnblogs.com/angeldevil/p/3729808.html
官方文檔:http://loopj.com/android-async-http/
代碼比較簡單就不附上DEMO了。
Android中android-async-http開源網路架構的簡單使用