ネットワークデータリクエスト実践1:android-async-httpダウンロードとアップロードを実現


android-async-httpは、android非同期ネットワークデータ要求フレームワークであり、ネットワーク処理はAndroidの非UIスレッドに基づいて、コールバック方法で要求結果を処理する.この記事では、その使い方を簡単に紹介し、ファイルのアップロードとダウンロードの機能を実現します.
一.android-async-httpの概要
  • オープンソースプロジェクトandroid-async-httpアドレス:https://github.com/loopj/android-async-http
  • 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実践
  • 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);
        }

    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;
            }
          }
    
    }

    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) {
    
            }
        }
    }

    4.呼び出し方法:MyImageDownLoaderのみで例示します.
    1)MyImageDownLoaderテスト関数(activityで実装):
    private static String URL_PHOTO = "http://img001.us.expono.com/100001/100001-1bc30-2d736f_m.jpg";
    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();
                            }
                        }
                    });
        }

    5プロジェクトdemoアドレス:
    https://github.com/ranke/HttpAsyncTest/tree/master/code/src/com/util/http
    オープンソースの力は無限だ!