Android实战——okhttp3的使用和封装

okhttp3的基本使用

1、Get请求
2、Post请求
3、文件上传
4、文件下载

okhttp3的导入

compile 'com.squareup.okio:okio:1.13.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'

okhttp3工具类的简单封装的演示

public class HttpUtils {
   private static volatile OkHttpClient okHttpClient;
   private static volatile Request request;
    public static OkHttpClient okhttp() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .addNetworkInterceptor(new TokenHeaderInterceptor())
                .build();
        return okHttpClient;
    }

    /**
     * @param baseUrl   //请求的URL
     * @param formBody  //请求参数,这里是post form表单请求
     * @return
     */
    public static Request request (String baseUrl, FormBody formBody ){
        //请求的url
        request = new Request.Builder()
                .url(baseUrl)//请求的url
                .post(formBody)
                .build();
        return request;
    }

    /**
     * 拦截器
     */
    public static class TokenHeaderInterceptor implements Interceptor {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            // get token
//            String token = AppService.getToken();
            Request originalRequest = chain.request();
            // get new request, add request header
            Request updateRequest = originalRequest.newBuilder()
                    //请求头
//                    .header("token", token)
                    .build();
            return chain.proceed(updateRequest);
        }
}
}

上传文件演示  获取进度的工具类

public class UploadFileRequestBody extends RequestBody {

    private RequestBody mRequestBody;
    private ProgressListener mProgressListener;
    private BufferedSink bufferedSink;
    private String fileName ;

    public UploadFileRequestBody(File file,  ProgressListener progressListener) {
        this.mRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        this.mProgressListener = progressListener;
        this.fileName = file.getName();
    }

    public UploadFileRequestBody(RequestBody requestBody, ProgressListener progressListener) {
        this.mRequestBody = requestBody;
        this.mProgressListener = progressListener;
    }

    //返回了requestBody的类型,想什么form-data/MP3/MP4/png等等等格式
    @Override
    public MediaType contentType() {
        return mRequestBody.contentType();
    }

    //返回了本RequestBody的长度,也就是上传的totalLength
    @Override
    public long contentLength() throws IOException {
        return mRequestBody.contentLength();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            //包装
            bufferedSink = Okio.buffer(sink(sink));
        }
        //写入
        mRequestBody.writeTo(bufferedSink);
        //必须调用flush,否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }

    private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            //当前写入字节数
            long bytesWritten = 0L;
            //总字节长度,避免多次调用contentLength()方法
            long contentLength = 0L;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if (contentLength == 0) {
                    //获得contentLength的值,后续不再调用
                    contentLength = contentLength();
                }
                //增加当前写入的字节数
                bytesWritten += byteCount;
                //回调上传接口
                mProgressListener.onProgress(bytesWritten, contentLength, bytesWritten == contentLength);
            }
        };
    }

    public String getFileName() {
        return fileName;
    }
}
// file 上传的文件
UploadFileRequestBody fileRequestBody = new UploadFileRequestBody(file, new ProgressListener() {
    @Override
    public void onProgress(long hasWrittenLen, long totalLen, boolean hasFinish) {
        //计算进度
        long l = hasWrittenLen * 100 / totalLen;
        Apollo.emit(EventConstant.SHANGCHUAN, l);
        Log.d("onProgress: ", l + "");
    }
});

接下来请求接口  fileRequestBody  参数传进去就可以了

 

下载文件演示

/**
 * 文件下载工具类(单例模式)
 */

public class DownloadUtil {
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;
    private File file;
    String fileName = "";
    String fileSize = "";
    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = ArtUtils.obtainAppComponentFromContext(MainApplication.getInstance()).okHttpClient();
    }
    /**
     * @param url          下载连接
     * @param destFileDir  下载的文件储存目录
     * @param destFileName 下载文件名称
     * @param listener     下载监听
     */
    public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        //异步请求
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                listener.onDownloadFailed(e,fileName,fileSize);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                //储存下载文件的目录
                File dir = new File(destFileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                try {
                    is = response.body().byteStream();
                    Headers headers = response.headers();
                    headers.size();
                    String name = headers.get("Content-Disposition");
                    Log.d("onResponse: ", headers.get("fileSize") + "");
                    Log.d("onResponse: ", headers.get("fileName") + "");
                    fileSize = headers.get("fileSize");
                    fileName = headers.get("fileName");
                    long total = response.body().contentLength();
                    file = new File(dir, fileName);
                    listener.onDownloadFile(fileName,fileSize);
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载中更新进度条
                        listener.onDownloading(progress, fileName, fileSize);
                    }
                    fos.flush();
                    //下载完成
                    listener.onDownloadSuccess(file, fileName, fileSize);
                } catch (Exception e) {
                    listener.onDownloadFailed(e, fileName,  fileSize);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {

                    }
                }
            }
        });
    }

    public interface OnDownloadListener {
        /**
         * 下载成功之后的文件
         */
        void onDownloadSuccess(File file, String name, String size);
        /**
         * 下载进度
         */
        void onDownloading(int progress, String name, String size);
        /**
         * 下载异常信息
         */
        void onDownloadFailed(Exception e, String fileName, String size);
        /**
         * 文件信息
         * @param fileName
         * @param size
         */
        void onDownloadFile( String fileName, String size);
    }
}

/** * @param url 下载连接 * @param destFileDir 下载的文件储存目录 * @param destFileName 下载文件名称 * @param listener 下载监听 */

DownloadUtil.get().download(“url ”, “url ”, “destFileName ”,
        new DownloadUtil.OnDownloadListener() {

            @Override
            public void onDownloadSuccess(File file, String fileName, String size) {
                Log.d("onDownloadSuccess: ",fileName1+"");
                    //下载成功
                
            }

            @Override
            public void onDownloading(int progress, String fileName, String size) {
                Log.d("onDownloading: ", progress + "" + fileName + "" + size);
                    //正在下载 进度
               
            }

            @Override
            public void onDownloadFailed(Exception e, String fileName, String size) {
                Log.d("onDownloading: ", e.getMessage() + "%。。。。");
                    //下载失败
                  
            }

            @Override
            public void onDownloadFile(String fileName, String size) {
               //文件信息
            }
        });

你可能感兴趣的:(Android,Okhttp的简单使用)