使用android-async-http开源项目 上传、下载文件

牛华皓
2023-12-01

准备工作

1、下载android-async-http.jar
2、将项目结构更换为project ,app→libs→导入jar包,右击该jar包→add to library

文件下载

//使用AsyncHttpClient 下载文件
    public void asyncDown(View view) {
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        final String url = editText.getText().toString().trim();
        asyncHttpClient.get(url, new BinaryHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                //获取外部存储 sdcard目录
                String filePath = Environment.getExternalStorageDirectory()+"/1.jpg";
                File file = new File(filePath);
                //压缩格式
                Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
                //压缩比例
                int quality = 100;
                try {
                    if(file.exists()){ //若文件存在,将文件删除
                        file.delete();
                    }
                    file.createNewFile(); //创建新文件
                    //打开输出流
                    OutputStream os = new FileOutputStream(file);
                    //压缩输出
                    bitmap.compress(format,quality,os);
                    os.close();
                    Toast.makeText(NetActivity.this,"图片下载成功",Toast.LENGTH_SHORT).show();


                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

文件上传

 //使用AsyncHttpClient 上传文件
    public void asyncUpload(View view) {
        String path = "/sdcard/4.jpg";
        String url= "http://127.0.0.1:8080/upload/"; //url需要改
        File file = new File(path);
        if(file.exists()&&file.length()>0){
            AsyncHttpClient client = new AsyncHttpClient();
            RequestParams params = new RequestParams();
            try {
                params.put("uploadfile",file);
                client.post(url,params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                            Toast.makeText(NetActivity.this,"图片上传成功",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        Toast.makeText(NetActivity.this,"图片上传失败",Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
        else {
            Toast.makeText(NetActivity.this,"图片不存在",Toast.LENGTH_SHORT).show();
        }

    }

可能遇到的问题

Header类未找到
解决方法:Android6.0后该类不在推荐使用,
builder.gradle (module:app)→Android结点里添加

 useLibrary 'org.apache.http.legacy'
 类似资料: