加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

android-async-http实现下载和上传

发布时间:2020-12-15 03:16:58 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 一.android-async-http简介 RequestParams params = new RequestParams();params.put("uid","00001");params.put("password","222221"); 二.android-a

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

一.android-async-http简介

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

二.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,params,res);
    }

    // 不带参数,获取json对象或者数组
    public static void get(String urlString,JsonHttpResponseHandler res) {
        client.get(urlString,res);
    }

    // 带参数,获取json对象或者数组
    public static void get(String urlString,res);
    }

    // 下载数据使用,会返回byte数据
    public static void get(String uString,BinaryHttpResponseHandler bHandler) {
        client.get(uString,bHandler);
    }

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

    //post
    public static void post(String urlString,ResponseHandlerInterface bHandler) {
        client.post(urlString,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,byte[] binaryData,Throwable error) {
            Log.i(TAG,"download failed");
        }  

        private boolean saveImage(byte[] binaryData,String savePath) {
            Bitmap bmp = BitmapFactory.decodeByteArray(binaryData,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,new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode,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,byte[] responseBody,Throwable error) {
                    Log.i(TAG," statusCode====binaryData len====="+ responseBody.length);
                    Log.i(TAG," statusCode====error====="+ error.getLocalizedMessage());

                }

            });

        } catch (FileNotFoundException e) {

        }
    }
}

4. 调用方法:仅以MyImageDownLoader 来举例说明。

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,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地址:


以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读