android-async-http實現下載和上傳

m45y 9年前發布 | 15K 次閱讀 Java Android

android-async-http,是一個android異步網絡數據請求框架,網絡處理均基于Android的非UI線程,通過回調方法處理請求結果。本篇簡單介紹一下它的用法,分別實現上傳和下載文件的功能。

一.android-async-http簡介

  1. 開源項目android-async-http地址:
    https://github.com/loopj/android-async-http

  2. android-async-http核心組件:
    a). AsyncHttpResponseHandler ——這是一個請求返回處理,成功,失敗,開始,完成,等自定義的消息的類;
    b). BinaryHttpResponseHandler extends AsyncHttpResponseHandler ——繼承AsyncHttpResponseHandler的子類,這是一個字節流返回處理的類, 該類用于處理圖片等類;
    c). JsonHttpResponseHandler extends AsyncHttpResponseHandler ——繼承AsyncHttpResponseHandler的子類,這是一個json請求返回處理服務器與客戶端用json交流時使用的類;
    d). AsyncHttpRequest implements Runnable ——基于線程的子類,用于 異步請求類, 通過AsyncHttpResponseHandler回調。
    e). PersistentCookieStore implements CookieStore ——這是一個基于CookieStore的子類, 使用HttpClient處理數據,并且使用cookie持久性存儲接口。

    f). RequestParams ——封裝了參數處理 例如:

RequestParams params = new RequestParams();
params.put("uid", "00001");
params.put("password", "111111");

核心操作類:
a). RetryHandler implements HttpRequestRetryHandler——這是一個多個線程同步處理的類;
b). SerializableCookie implements Serializable——這是操作cookie 放入/取出數據的類;
c). SimpleMultipartEntity implements HttpEntity——用于處理多個請求實體封裝;
d). SyncHttpClient extends AsyncHttpClient——同步客戶端請求的類;
e). AsyncHttpClient——異步客戶端請求的類。

二.android-async-http實踐

  1. HttpClientUtil封裝類的實現:
    這個class對AsyncHttpClient進行了封裝。

public class HttpClientUtil {
    // 實例話對象
    private static AsyncHttpClient client = new AsyncHttpClient();
    static {

    client.setTimeout(11000); // 設置鏈接超時,如果不設置,默認為10s
}

public static AsyncHttpClient getClient() {
    return client;
}

// 用一個完整url獲取一個string對象
public static void get(String urlString, AsyncHttpResponseHandler res) {
    client.get(urlString, res);
}

// url里面帶參數
public static void get(String urlString, RequestParams params,
        AsyncHttpResponseHandler res) {
    client.get(urlString, params, res);
}

// 不帶參數,獲取json對象或者數組
public static void get(String urlString, JsonHttpResponseHandler res) {
    client.get(urlString, res);
}

// 帶參數,獲取json對象或者數組
public static void get(String urlString, RequestParams params,
        JsonHttpResponseHandler res) {
    client.get(urlString, params, res);
}

// 下載數據使用,會返回byte數據
public static void get(String uString, BinaryHttpResponseHandler bHandler) {
    client.get(uString, bHandler);
}

//多個url?
public static void get(String urlString, RequestParams params,
        BinaryHttpResponseHandler bHandler) {
    client.get(urlString, params, bHandler);
}

//post
public static void post(String urlString, RequestParams params,
        ResponseHandlerInterface bHandler) {
    client.post(urlString, params, bHandler);
}</pre> 


2. MyImageDownLoader的實現:

提供了下載圖片的函數

  public class MyImageDownLoader {

private static final String TAG = "MyImageDownLoader";

Context mContext;

public interface DownLoaderListener {
    public void onResult(int res, String s);
}

public MyImageDownLoader() {

}


//download image public void downloadImage(String uri, String savePath, DownLoaderListener downLoaderListener){
// 指定文件類型
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };

    HttpClientUtil.get(uri, new ImageResponseHandler(allowedContentTypes,savePath, downLoaderListener));  
  }  

  public class ImageResponseHandler extends BinaryHttpResponseHandler{  
      private String[] allowedContentTypes;  
      private String savePathString;
      DownLoaderListener mDownLoaderListener;

      public ImageResponseHandler(String[] allowedContentTypes, String path, DownLoaderListener downLoaderListener){  
          super();  
          this.allowedContentTypes = allowedContentTypes;  
          savePathString = path;
          mDownLoaderListener = downLoaderListener;
      }  

    @Override
    public void onSuccess(int statusCode, Header[] headers,
            byte[] binaryData) {
        Log.i(TAG, " statusCode=========" + statusCode);
        Log.i(TAG, " statusCode=========" + headers);
        Log.i(TAG, " statusCode====binaryData len=====" + binaryData.length);
        if (statusCode == 200 && binaryData!=null && binaryData.length > 0) {
            boolean b = saveImage(binaryData,savePathString); 
            if (b) {

                mDownLoaderListener.onResult(0, savePathString);


            }
            else {
                //fail
                mDownLoaderListener.onResult(-1, savePathString);
            }
        }
    }
    @Override
    public void onFailure(int statusCode, Header[] headers,
            byte[] binaryData, Throwable error) {
        Log.i(TAG, "download failed");
    }  

    private boolean saveImage(byte[] binaryData, String savePath) {
        Bitmap bmp = BitmapFactory.decodeByteArray(binaryData, 0,  
                binaryData.length);  

        Log.i(TAG,"saveImage==========" +  savePath);
        File file = new File(savePath);  
        // 壓縮格式  
        CompressFormat format = Bitmap.CompressFormat.JPEG;  
        // 壓縮比例  
        int quality = 100;  
        try {  
            if (file.createNewFile()){
                OutputStream stream = new FileOutputStream(file);  
                // 壓縮輸出  
                bmp.compress(format, quality, stream);  
                stream.close();  
                return true;
            }

        } catch (IOException e) { 
            Log.i(TAG,"saveImage====003======" +  savePath);
            e.printStackTrace();  
        }  
        Log.i(TAG,"saveImage====004======" +  savePath);
        return false;
    }
  }

}</pre>

3. HttpAsyncUploader的實現:

/**

  • 異步上傳單個文件 */ public class HttpAsyncUploader { private static final String TAG = "HttpAsyncUploader";

    Context mContext;

    public HttpAsyncUploader() { }

    public void uploadFile(String uri, String path) {

     File file = new File(path);
     RequestParams params = new RequestParams();
    
     try {
         params.put("image", file, "application/octet-stream");
    
         AsyncHttpClient client = new AsyncHttpClient();
    
         HttpClientUtil.post(path, params, new AsyncHttpResponseHandler() {
             @Override
             public void onSuccess(int statusCode, Header[] headers,
                     byte[] responseBody) {
                 Log.i(TAG, " statusCode=========" + statusCode);
                 Log.i(TAG, " statusCode=========" + headers);
                 Log.i(TAG, " statusCode====binaryData len====="+ responseBody.length);
             }
    
             @Override
             public void onFailure(int statusCode, Header[] headers,
                     byte[] responseBody, Throwable error) {
                 Log.i(TAG, " statusCode=========" + statusCode);
                 Log.i(TAG, " statusCode=========" + headers);
                 Log.i(TAG, " statusCode====binaryData len====="+ responseBody.length);
                 Log.i(TAG," statusCode====error====="+ error.getLocalizedMessage());
    
             }
    
         });
    
     } catch (FileNotFoundException e) {
    
     }
    

    } }</pre>

    4. 調用方法:僅以MyImageDownLoader 來舉例說明。

    1)MyImageDownLoader 測試函數(在activity中實現):

    private static String URL_PHOTO = "http://img001.us.expono.com/100001/100001-1bc30-2d736f_m.jpg&quot;;
    private void downloadTest() {
     String url =URL_PHOTO;
     String fileName = "" + System.currentTimeMillis() + ".jpg";
     String savePath = mContext.getCacheDir() + File.separator + fileName;
     MyImageDownLoader mMyImageDownLoader = new MyImageDownLoader();

     // 開始異步下載
    

    mMyImageDownLoader.downloadImage(

         url,
         savePath,
         new DownLoaderListener() {
             @Override
             public void onResult(int res, String s) {
                 Log.i(TAG,"onResult====res===" + res);
                 Log.i(TAG, "onResult====s===" + s);
                 if (res == 0) {
                     // 下載成功
                     Toast.makeText(mContext, "download success!", Toast.LENGTH_LONG).show();
                     } else {
                         // 下載photo失敗
                         Toast.makeText(mContext, "download fail!", Toast.LENGTH_LONG).show();
                     }
                 }
             });
    

    }</pre>

    5 項目demo地址:

    https://github.com/ranke/HttpAsyncTest/tree/master/code/src/com/util/http


 本文由用戶 m45y 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!