Android开发 retrofit下载与上传

时间:2022-11-09 18:39:00

前言

   此博客只讲解retrofit下载与上传的使用,其实与其说是retrofit的下载与上传还不如说,依然是Okhttp的下载与上传.如果你需要了解retrofit入门请查看这篇博客(此博客不在详细讲解一些基础的东西):https://www.cnblogs.com/guanxinjing/p/11594249.html

下载

  设置下载接口

public interface HttpList {

    @Streaming //注解这个请求将获取数据流,此后将不会这些获取的请求数据保存到内存中,将交与你操作.
    @GET
    Call<ResponseBody> download(@Url String url);


}

  请求下载

private void downloadFile() {
        final File file = new File(getExternalCacheDir(), "demo.apk");
        if (file.exists()) {
            file.delete();
        }

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://p.gdown.baidu.com/")//base的网络地址
                .callbackExecutor(Executors.newSingleThreadExecutor())//设置线程,如果不设置下载在读取流的时候就会报错
                .build();

        HttpList httpList = retrofit.create(HttpList.class);

        Call<ResponseBody> call = httpList.download(DOWNLOAD_URL_PATH);//下载地址  太长了所以我用DOWNLOAD_URL_PATH封装了一下,不要误解

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    long total = response.body().contentLength();//需要下载的总大小
                    long current = 0;
                    InputStream inputStream = response.body().byteStream();
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(bytes)) != -1) {
                        fileOutputStream.write(bytes);
                        current = current   len;
                        Log.e(TAG, "已经下载="   current   " 需要下载="   total);
                    }
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    inputStream.close();

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

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

以上的下载实现的关键点,其实是ResponseBody,而这个其实就是okhttp的请求接口后返回的响应body. Retrofit并没有对这个进行封装,所以如果你了解okhttp的使用,应该是轻轻松松的.

 

上传

 

 

 

 

 

 

 

 

 

 

 

 

 

end