okhttp 文件上传下载

本文介绍了一种在Android应用中实现文件上传和下载的方法。通过使用OkHttp进行网络请求,文章详细展示了如何将本地文件上传至服务器,并从服务器下载文件到本地的过程。包括创建请求、处理响应以及使用Handler更新UI等关键步骤。

public void uploadfile(final Context context, final String id, final String account) throws IOException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String name = id + "_" + account + ".zip";
                    Log.d(TAG, "已登录,上传数据 账号 account 文章 yid");
                    String url = "你的上传地址";
                    File file = new File(Environment.getExternalStorageDirectory().toString() + "/record", name);
                    if (!file.exists()) {
                        Log.d(TAG, "文件不存在");
                        Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.d(TAG, "文件存在");
                        RequestBody formBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("file", name(这个name就是上传到服务器的名字), RequestBody.create(MediaType.parse("text/plain"), file))
                                .addFormDataPart("account", account)
                                .addFormDataPart("yid", id)
                                .build();
                        Request request = new Request.Builder().url(url).post(formBody).build();
                        Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) {
                            Log.d(TAG, "上传失败");
                            throw new IOException("Unexpected code " + response);
                        } else {
                            handler.sendEmptyMessage(MSG_SUCCESS);
                            Log.d(TAG, "上传成功");
                        }
                        Log.d(TAG, response.body().string());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

注册成功的信息通过Handler来发送

    private static final int MSG_SUCCESS = 0;
    private static final int MSG_SUCCESS_DOWNLOAD = 1;

    Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_SUCCESS :
                    Toast.makeText(context, "上传成功", Toast.LENGTH_LONG).show();
                    break;
                case MSG_SUCCESS_DOWNLOAD :
                    Toast.makeText(context,"下载成功",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

下载

  public void downloadfile(final String name) throws IOException, InterruptedException {
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "downloadfile 开始");
                int cacheSize = 10 * 1024 * 1024; // 10 MiB
                File sdcache = new File(String.valueOf(Environment.getExternalStorageDirectory()) + "/com.jinjie.yuyin/wav");
                Cache cache = new Cache(sdcache.getAbsoluteFile(), cacheSize);
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.cache(cache);
                client = builder.build();
                //传入文件的名字
                RequestBody formBody = new FormBody.Builder()
                        .add("name", name)
                        .build();

                Request request = new Request.Builder()
                        .url("下载地址")
                        .post(formBody)
                        .build();
                try {
                    response = client.newCall(request).execute();
                    if (!response.isSuccessful()) {
                        Log.d(TAG, "下载失败");
                        throw new IOException("Unexpected code " + response);
                    } else {
                        Log.d(TAG, "返回数据成功,开始写入");
                        InputStream is;
                        is = response.body().byteStream();
                        FileOutputStream fos;
                        String pa = Environment.getExternalStorageDirectory().toString();
                        File ff = new File(pa + "/com.jinjie.yuyin/wav",name+".zip");
                        if (!ff.exists()) {
                            ff.createNewFile();
                        }
                        fos = new FileOutputStream(ff);
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while ((len = is.read(bytes)) != -1) {
                            fos.write(bytes, 0, len);
                        }
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t2.start();
        Log.d(TAG, "结束");
        handler.sendEmptyMessage(MSG_SUCCESS_DOWNLOAD);
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值