• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            牽著老婆滿街逛

            嚴(yán)以律己,寬以待人. 三思而后行.
            GMail/GTalk: yanglinbo#google.com;
            MSN/Email: tx7do#yahoo.com.cn;
            QQ: 3 0 3 3 9 6 9 2 0 .

            Android Asynchronous Http Client-Android異步網(wǎng)絡(luò)請求客戶端接口

            轉(zhuǎn)載自:http://blog.csdn.net/hil2000/article/details/13949513

            1.簡介
            Android中網(wǎng)絡(luò)請求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用這兩個類庫需要寫大量的代碼才能完成網(wǎng)絡(luò)post和get請求,而使用android-async-http這個庫可以大大的簡化操作,它是基于Apache’s HttpClient ,所有的請求都是獨立在UI主線程之外,通過回調(diào)方法處理請求結(jié)果,采用android  Handler message 機制傳遞信息。

            2.特性
            (1)采用異步http請求,并通過匿名內(nèi)部類處理回調(diào)結(jié)果
            (2)http請求獨立在UI主線程之外
            (3)采用線程池來處理并發(fā)請求
            (4)采用RequestParams類創(chuàng)建GET/POST參數(shù)
            (5)不需要第三方包即可支持Multipart file文件上傳
            (6)大小只有25kb
            (7)自動為各種移動電話處理連接斷開時請求重連
            (8)超快的自動gzip響應(yīng)解碼支持
            (9)使用BinaryHttpResponseHandler類下載二進制文件(如圖片)
            (10) 使用JsonHttpResponseHandler類可以自動將響應(yīng)結(jié)果解析為json格式
            (11)持久化cookie存儲,可以將cookie保存到你的應(yīng)用程序的SharedPreferences中


            3.使用方法
            (1)到官網(wǎng)http://loopj.com/android-async-http/下載最新的android-async-http-1.4.4.jar,然后將此jar包添加進Android應(yīng)用程序 libs文件夾
            (2)通過import com.loopj.android.http.*;引入相關(guān)類
            (3)創(chuàng)建異步請求

            [java] view plain copy
            1. AsyncHttpClient client = new AsyncHttpClient();  
            2. client.get("http://www.google.com", new AsyncHttpResponseHandler() {  
            3.     @Override  
            4.     public void onSuccess(String response) {  
            5.         System.out.println(response);  
            6.     }  
            7. });  

            4.建議使用靜態(tài)的Http Client對象
            在下面這個例子,我們創(chuàng)建了靜態(tài)的http client對象,使其很容易連接到Twitter的API
            [java] view plain copy
            1. import com.loopj.android.http.*;  
            2.   
            3. public class TwitterRestClient {  
            4.   private static final String BASE_URL = "http://api.twitter.com/1/";  
            5.   
            6.   private static AsyncHttpClient client = new AsyncHttpClient();  
            7.   
            8.   public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {  
            9.       client.get(getAbsoluteUrl(url), params, responseHandler);  
            10.   }  
            11.   
            12.   public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {  
            13.       client.post(getAbsoluteUrl(url), params, responseHandler);  
            14.   }  
            15.   
            16.   private static String getAbsoluteUrl(String relativeUrl) {  
            17.       return BASE_URL + relativeUrl;  
            18.   }  
            19. }  
            然后我們可以很容易的在代碼中操作Twitter的API
            [java] view plain copy
            1. import org.json.*;  
            2. import com.loopj.android.http.*;  
            3.   
            4. class TwitterRestClientUsage {  
            5.     public void getPublicTimeline() throws JSONException {  
            6.         TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {  
            7.             @Override  
            8.             public void onSuccess(JSONArray timeline) {  
            9.                 // Pull out the first event on the public timeline  
            10.                 JSONObject firstEvent = timeline.get(0);  
            11.                 String tweetText = firstEvent.getString("text");  
            12.   
            13.                 // Do something with the response  
            14.                 System.out.println(tweetText);  
            15.             }  
            16.         });  
            17.     }  
            18. }  

            5. AsyncHttpClient, RequestParams ,AsyncHttpResponseHandler三個類使用方法

            (1)AsyncHttpClient
            public class AsyncHttpClient extends java.lang.Object
             該類通常用在android應(yīng)用程序中創(chuàng)建異步GET, POST, PUT和DELETE HTTP請求,請求參數(shù)通過RequestParams實例創(chuàng)建,響應(yīng)通過重寫匿名內(nèi)部類 ResponseHandlerInterface的方法處理。
            例子:
            [java] view plain copy
            1. AsyncHttpClient client = new AsyncHttpClient();  
            2.  client.get("http://www.google.com", new ResponseHandlerInterface() {  
            3.      @Override  
            4.      public void onSuccess(String response) {  
            5.          System.out.println(response);  
            6.      }  
            7.  });  
            (2)RequestParams
            public class RequestParams extends java.lang.Object 
            用于創(chuàng)建AsyncHttpClient實例中的請求參數(shù)(包括字符串或者文件)的集合
            例子:
            [java] view plain copy
            1. RequestParams params = new RequestParams();  
            2.  params.put("username", "james");  
            3.  params.put("password", "123456");  
            4.  params.put("email", "my@email.com");  
            5.  params.put("profile_picture", new File("pic.jpg")); // Upload a File  
            6.  params.put("profile_picture2", someInputStream); // Upload an InputStream  
            7.  params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes  
            8.   
            9.  Map<String, String> map = new HashMap<String, String>();  
            10.  map.put("first_name", "James");  
            11.  map.put("last_name", "Smith");  
            12.  params.put("user", map); // url params: "user[first_name]=James&user[last_name]=Smith"  
            13.   
            14.  Set<String> set = new HashSet<String>(); // unordered collection  
            15.  set.add("music");  
            16.  set.add("art");  
            17.  params.put("like", set); // url params: "like=music&like=art"  
            18.   
            19.  List<String> list = new ArrayList<String>(); // Ordered collection  
            20.  list.add("Java");  
            21.  list.add("C");  
            22.  params.put("languages", list); // url params: "languages[]=Java&languages[]=C"  
            23.   
            24.  String[] colors = { "blue", "yellow" }; // Ordered collection  
            25.  params.put("colors", colors); // url params: "colors[]=blue&colors[]=yellow"  
            26.   
            27.  List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();  
            28.  Map<String, String> user1 = new HashMap<String, String>();  
            29.  user1.put("age", "30");  
            30.  user1.put("gender", "male");  
            31.  Map<String, String> user2 = new HashMap<String, String>();  
            32.  user2.put("age", "25");  
            33.  user2.put("gender", "female");  
            34.  listOfMaps.add(user1);  
            35.  listOfMaps.add(user2);  
            36.  params.put("users", listOfMaps); // url params: "users[][age]=30&users[][gender]=male&users[][age]=25&users[][gender]=female"  
            37.   
            38.  AsyncHttpClient client = new AsyncHttpClient();  
            39.  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)方法
            例子:
            [java] view plain copy
            1. AsyncHttpClient client = new AsyncHttpClient();  
            2.  client.get("http://www.google.com", new AsyncHttpResponseHandler() {  
            3.      @Override  
            4.      public void onStart() {  
            5.          // Initiated the request  
            6.      }  
            7.   
            8.      @Override  
            9.      public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {  
            10.          // Successfully got a response  
            11.      }  
            12.   
            13.      @Override  
            14.      public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)  
            15.  {  
            16.          // Response failed :(  
            17.      }  
            18.   
            19.      @Override  
            20.      public void onRetry() {  
            21.          // Request was retried  
            22.      }  
            23.   
            24.      @Override  
            25.      public void onProgress(int bytesWritten, int totalSize) {  
            26.          // Progress notification  
            27.      }  
            28.   
            29.      @Override  
            30.      public void onFinish() {  
            31.          // Completed the request (either success or failure)  
            32.      }  
            33.  });  

            6.利用PersistentCookieStore持久化存儲cookie
            PersistentCookieStore類用于實現(xiàn)Apache HttpClient的CookieStore接口,可以自動的將cookie保存到Android設(shè)備的SharedPreferences中,如果你打算使用cookie來管理驗證會話,這個非常有用,因為用戶可以保持登錄狀態(tài),不管關(guān)閉還是重新打開你的app
            (1)首先創(chuàng)建 AsyncHttpClient實例對象
            [java] view plain copy
            1. AsyncHttpClient myClient = new AsyncHttpClient();  
            (2)將客戶端的cookie保存到PersistentCookieStore實例對象,帶有activity或者應(yīng)用程序context的構(gòu)造方法
            [java] view plain copy
            1. PersistentCookieStore myCookieStore = new PersistentCookieStore(this);  
            2. myClient.setCookieStore(myCookieStore);  
            (3)任何從服務(wù)器端獲取的cookie都會持久化存儲到myCookieStore中,添加一個cookie到存儲中,只需要構(gòu)造一個新的cookie對象,并且調(diào)用addCookie方法
            [java] view plain copy
            1. BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");  
            2. newCookie.setVersion(1);  
            3. newCookie.setDomain("mydomain.com");  
            4. newCookie.setPath("/");  
            5. myCookieStore.addCookie(newCookie);  

            7.利用RequestParams上傳文件
            類RequestParams支持multipart file 文件上傳
            (1)在RequestParams 對象中添加InputStream用于上傳
            [java] view plain copy
            1. InputStream myInputStream = blah;  
            2. RequestParams params = new RequestParams();  
            3. params.put("secret_passwords", myInputStream, "passwords.txt");  
            (2)添加文件對象用于上傳
            [java] view plain copy
            1. File myFile = new File("/path/to/file.png");  
            2. RequestParams params = new RequestParams();  
            3. try {  
            4.     params.put("profile_picture", myFile);  
            5. } catch(FileNotFoundException e) {}  
            (3)添加字節(jié)數(shù)組用于上傳
            [java] view plain copy
            1. byte[] myByteArray = blah;  
            2. RequestParams params = new RequestParams();  
            3. params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");  

            8.用BinaryHttpResponseHandler下載二進制數(shù)據(jù)
            [java] view plain copy
            1. BinaryHttpResponseHandler用于獲取二進制數(shù)據(jù)如圖片和其他文件  
            2. AsyncHttpClient client = new AsyncHttpClient();  
            3. String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };  
            4. client.get("http://example.com/file.png", new BinaryHttpResponseHandler(allowedContentTypes) {  
            5.     @Override  
            6.     public void onSuccess(byte[] fileData) {  
            7.         // Do something with the file  
            8.     }  
            9. });  

            參考資料:http://loopj.com/android-async-http/

            posted on 2016-02-19 10:37 楊粼波 閱讀(278) 評論(0)  編輯 收藏 引用


            只有注冊用戶登錄后才能發(fā)表評論。
            網(wǎng)站導(dǎo)航: 博客園   IT新聞   BlogJava   博問   Chat2DB   管理


            亚洲午夜无码久久久久| 久久九九亚洲精品| 少妇久久久久久久久久| 99久久精品国产免看国产一区| 91精品国产91热久久久久福利| 人妻丰满?V无码久久不卡| 无码AV中文字幕久久专区| 久久精品国产99久久香蕉| 无码久久精品国产亚洲Av影片 | 久久国产精品久久| 亚洲欧洲久久av| 大香网伊人久久综合网2020| 国产亚洲美女精品久久久2020| 国产AⅤ精品一区二区三区久久| 狠狠色丁香久久婷婷综合图片 | 久久国产综合精品五月天| 77777亚洲午夜久久多喷| 久久国产精品一区| 青青草国产成人久久91网| 奇米影视7777久久精品| 久久精品中文字幕一区| 精品99久久aaa一级毛片| 久久综合九色综合精品| 波多野结衣中文字幕久久| 久久人人爽人人爽人人片av麻烦 | 亚洲精品午夜国产VA久久成人| 91久久九九无码成人网站| 97精品久久天干天天天按摩| 一本一道久久综合狠狠老| 青青草原综合久久大伊人导航| 亚洲综合久久综合激情久久| 国产午夜精品久久久久免费视 | 久久精品亚洲精品国产欧美| 国产99精品久久| 99麻豆久久久国产精品免费| 久久精品人人做人人爽电影蜜月| 亚洲天堂久久久| 国产成人精品综合久久久| 久久久久久久女国产乱让韩| 久久久亚洲欧洲日产国码是AV| 青青草原综合久久大伊人|