[摘要:1.簡介 Android中收集要求一樣平常應(yīng)用Apache HTTP Client或采納HttpURLConnect,然則間接應(yīng)用那兩個類庫須要寫大批的代碼才干完成收集post戰(zhàn)get要求,而應(yīng)用android-async-http那個庫能夠大大的簡化]
Android中網(wǎng)絡(luò)請求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用這兩個類庫需要寫大量的代碼才能完成網(wǎng)絡(luò)post和get請求,而使用android-async-http這個庫可以大大的簡化操作,它是基于Apache’s HttpClient ,所有的請求都是獨(dú)立在UI主線程之外,通過回調(diào)方法處理請求結(jié)果,采用android Handler message 機(jī)制傳遞信息。
(1)采用異步http請求,并通過匿名內(nèi)部類處理回調(diào)結(jié)果 (2)http請求獨(dú)立在UI主線程之外 (3)采用線程池來處理并發(fā)請求 (4)采用RequestParams類創(chuàng)建GET/POST參數(shù) (5)不需要第三方包即可支持Multipart file文件上傳 (6)大小只有25kb (7)自動為各種移動電話處理連接斷開時請求重連 (8)超快的自動gzip響應(yīng)解碼支持 (9)使用BinaryHttPResponseHandler類下載二進(jìn)制文件(如圖片) (10) 使用JsonHttpResponseHandler類可以自動將響應(yīng)結(jié)果解析為json格式 (11)持久化cookie存儲,可以將cookie保存到你的應(yīng)用程序的SharedPreferences中
(1)到官網(wǎng)http://loopj.com/android-async-http/下載最新的android-async-http-1.4.9.jar,然后將此jar包添加進(jìn)Android應(yīng)用程序 libs文件夾 (2)通過import com.loopj.android.http.*;引入相關(guān)類 (3)創(chuàng)建異步請求
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.google.com", new AsyncHttpResponseHandler() { @Override public void onSuccess(String response) { System.out.println(response); } });**
** 在下面這個例子,我們創(chuàng)建了靜態(tài)的http client對象,使其很容易連接到Twitter的API [java] view plaincopy
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; } }然后我們可以很容易的在代碼中操作Twitter的API
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(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); } }); } } AsyncHttpClient, RequestParams ,AsyncHttpResponseHandler 三個類使用方法 (1)AsyncHttpClient public class AsyncHttpClient extends java.lang.Object 該類通常用在android應(yīng)用程序中創(chuàng)建異步GET, POST, PUT和DELETE HTTP請求,請求參數(shù)通過RequestParams實(shí)例創(chuàng)建,響應(yīng)通過重寫匿名內(nèi)部類 ResponseHandlerInterface的方法處理。 例子:AsyncHttpClient client = new AsyncHttpClient(); client.get("http://www.google.com", new ResponseHandlerInterface() { @Override public void onSuccess(String response) { System.out.println(response); } });(2)RequestParams public class RequestParams extends java.lang.Object 用于創(chuàng)建AsyncHttpClient實(shí)例中的請求參數(shù)(包括字符串或者文件)的集合 例子:
RequestParams params = new RequestParams(); params.put("username", "james"); params.put("passWord", "123456"); params.put("email", "my@email.com"); params.put("profile_picture", new File("pic.jpg")); // Upload a File params.put("profile_picture2", someInputStream); // Upload an InputStream params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes Map<String, String> map = new HashMap<String, String>(); map.put("first_name", "James"); map.put("last_name", "Smith"); params.put("user", map); // url params: "user[first_name]=James&user[last_name]=Smith" Set<String> set = new HashSet<String>(); // unordered collection set.add("music"); set.add("art"); params.put("like", set); // url params: "like=music&like=art" List<String> list = new ArrayList<String>(); // Ordered collection list.add("Java"); list.add("C"); params.put("languages", list); // url params: "languages[]=Java&languages[]=C" String[] colors = { "blue", "yellow" }; // Ordered collection params.put("colors", colors); // url params: "colors[]=blue&colors[]=yellow" List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>(); Map<String, String> user1 = new HashMap<String, String>(); user1.put("age", "30"); user1.put("gender", "male"); Map<String, String> user2 = new HashMap<String, String>(); user2.put("age", "25"); user2.put("gender", "female"); listOfMaps.add(user1); listOfMaps.add(user2); params.put("users", listOfMaps); // url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female" AsyncHttpClient client = new AsyncHttpClient(); client.post("http://myendpoint.com", params, responseHandler);(3)public class AsyncHttpResponseHandler extends java.lang.Object implements ResponseHandlerInterface 用于攔截和處理由AsyncHttpClient創(chuàng)建的請求。在匿名類AsyncHttpResponseHandler中的重寫 onSuccess(int, org.apache.http.Header[], byte[])方法用于處理響應(yīng)成功的請求。此外,你也可以重寫 onFailure(int, org.apache.http.Header[], byte[], Throwable), onStart(), onFinish(), onRetry() 和onProgress(int, int)方法 例子:
AsyncHttpClient client = new AsyncHttpClient(); client.get("http://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() { // Request was retried } @Override public void onProgress(int bytesWritten, int totalSize) { // Progress notification } @Override public void onFinish() { // Completed the request (either success or failure) } });PersistentCookieStore類用于實(shí)現(xiàn)Apache HttpClient的CookieStore接口,可以自動的將cookie保存到Android設(shè)備的SharedPreferences中,如果你打算使用cookie來管理驗(yàn)證會話,這個非常有用,因?yàn)橛脩艨梢员3值卿洜顟B(tài),不管關(guān)閉還是重新打開你的app (1)首先創(chuàng)建 AsyncHttpClient實(shí)例對象
AsyncHttpClient myClient = new AsyncHttpClient();(2)將客戶端的cookie保存到PersistentCookieStore實(shí)例對象,帶有activity或者應(yīng)用程序context的構(gòu)造方法
PersistentCookieStore myCookieStore = new PersistentCookieStore(this); myClient.setCookieStore(myCookieStore);(3)任何從服務(wù)器端獲取的cookie都會持久化存儲到myCookieStore中,添加一個cookie到存儲中,只需要構(gòu)造一個新的cookie對象,并且調(diào)用addCookie方法
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome"); newCookie.setVersion(1); newCookie.setDomain("mydomain.com"); newCookie.setPath("/"); myCookieStore.addCookie(newCookie);7.利用RequestParams上傳文件 類RequestParams支持multipart file 文件上傳 (1)在RequestParams 對象中添加InputStream用于上傳
InputStream myInputStream = blah; RequestParams params = new RequestParams(); params.put("secret_passwords", myInputStream, "passwords.txt");(2)添加文件對象用于上傳
File myFile = new File("/path/to/file.png"); RequestParams params = new RequestParams(); try { params.put("profile_picture", myFile); } catch(FileNotFoundException e) {}(3)添加字節(jié)數(shù)組用于上傳
byte[] myByteArray = blah; RequestParams params = new RequestParams(); params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");8.用BinaryHttpResponseHandler下載二進(jìn)制數(shù)據(jù)
BinaryHttpResponseHandler用于獲取二進(jìn)制數(shù)據(jù)如圖片和其他文件 AsyncHttpClient client = new AsyncHttpClient(); String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" }; client.get("http://example.com/file.png", new BinaryHttpResponseHandler(allowedContentTypes) { @Override public void onSuccess(byte[] fileData) { // Do something with the file } });android-async-http 開源框架可以使我們輕松地獲取網(wǎng)絡(luò)數(shù)據(jù)或者向服務(wù)器發(fā)送數(shù)據(jù),最關(guān)鍵的是,它是異步框架,在底層使用線程池處理并發(fā)請求,效率很高,使用又特別簡單。
以往我們在安卓上做項(xiàng)目,比如要下載很多圖片、網(wǎng)頁或者其他的資源,多數(shù)開發(fā)者會選擇一個線程一個下載任務(wù)這種模型,因?yàn)榘沧孔詭У?AndroidHttpClient 或者 java 帶的 java.net.URL ,默認(rèn)都是阻塞式操作。這種模型效率不高,對并發(fā)要求高的 APP 來講,并不適用。有的人會選擇使用 nio 自己實(shí)現(xiàn),代碼復(fù)雜度又很高。AsyncHttpClient 作為 android-async-http 框架的一個核心應(yīng)用類,使用簡單,下面提供一些代碼來看如何使用:
public class Downloader { public static AsyncHttpClient mHttpc = new AsyncHttpClient(); public static String TAG = "Downloader"; public void downloadText(String uri){ mHttpc.get(uri, null, new AsyncHttpResponseHandler(){ @Override public void onSuccess(String data){ Log.i(TAG, "downloaded, thread id " + Thread.currentThread().getId()); // TODO: do something on } @Override public void onFailure(Throwable e, String data){ Log.i(TAG, "download failed."); // TODO: error proceed } }); } public void downloadImage(String uri, String savePath){ mHttpc.get(uri, new ImageResponseHandler(savePath)); } public class ImageResponseHandler extends BinaryHttpResponseHandler{ private String mSavePath; public ImageResponseHandler(String savePath){ super(); mSavePath = savePath; } @Override public void onSuccess(byte[] data){ Log.i(TAG, "download image, file length " + data.length); // TODO: save image , do something on image } @Override public void onFailure(Throwable e, String data){ Log.i(TAG, "download failed"); // TODO : error proceed } } };上面的代碼演示了如何使用 AsyncHttpResponseHandler 和 BinaryHttpResponseHandler ,相信 AsyncHttpClient 會給大家?guī)砗艽蟮谋憷?AsyncHttpClient框架下載地址:http://loopj.com/android-async-http/
新聞熱點(diǎn)
疑難解答
圖片精選