OkHttp使用指南

一、OKHttp的下载地址

Github的OkHttp资源

二、个人封装的简单工具类

public class OkHttp3Util {

    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
    private final static int TIMEOUTS = 20;
    private static OkHttp3Util mOkHttpUtil;
    private static MediaType MEDIATYPE_JSON;
    private static OkHttpClient mOkHttpClient;
    private static List<Call> mCallList;

    static {
        MEDIATYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    }

    private OkHttp3Util() {

    }

    public static OkHttp3Util getInstance() {

        if (mOkHttpUtil == null) {
            mOkHttpUtil = new OkHttp3Util();
            mOkHttpClient = new OkHttpClient();

            mOkHttpClient.newBuilder().connectTimeout(TIMEOUTS, TimeUnit.SECONDS) // 连接时长,TimeUnit.SECONDS表示时间单位为秒
                    .readTimeout(TIMEOUTS, TimeUnit.SECONDS) // 连接时长
                    .writeTimeout(TIMEOUTS, TimeUnit.SECONDS)// 读写时长
                    .retryOnConnectionFailure(false)// 失败不重试
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    });
        }

        if (mCallList == null) {
            mCallList = new ArrayList<Call>();
        }
        return mOkHttpUtil;
    }

    /**
     * 异步post请求
     *
     * @param tag        标签
     * @param url
     * @param paramsJson
     * @param callback
     */
    public void postAsy(String tag, String url, JSONObject paramsJson, Callback callback) {

        RequestBody paramsBody = RequestBody.create(MEDIATYPE_JSON, JSON.toJSONString(paramsJson));
        Request request = new Request.Builder().url(url).post(paramsBody).tag(tag).build();
        Call call = mOkHttpClient.newCall(request);
        mCallList.add(call);
        call.enqueue(callback);
    }

    /**
     * 取消请求
     *
     * @param tag
     */
    public void cancleReuqst(String tag) {
        for (Call call : mCallList) {
            if (call.request().tag().equals(tag)) {
                call.cancel();
                break;
            }
        }
    }

    public void upload(final String url, final String filePath, final String fileName) {
        File file = new File(filePath);
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);

        Request request = new Request.Builder().url(url).post(fileBody).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                call.cancel();
                Logger.e("文件上传", "onResponse " + response.toString());
            }

            @Override
            public void onFailure(Call call, IOException ex) {
                call.cancel();
                Logger.e("文件上传", "onFailure " + ex.toString());
            }
        });
    }

	
    public void uploadImgs(String url, List<String> imgPaths) {
		MultipartBuilder buidler = new MultipartBuilder().type(MultipartBuilder.FORM);

		for (String imgPath : imgPaths) {
			buidler.addFormDataPart("upload", null, RequestBody.create(MediaType.parse("image/png"), new File(imgPath)));
		}

		RequestBody requestBody = buidler.build();

		Request request = new Request.Builder().url(url).post(requestBody).build();

		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				Logger.e("文件上传", "onResponse " + response.toString());
			}

			@Override
			public void onFailure(Call call, IOException ex) {
				Logger.e("文件上传", "onFailure " + ex.toString());

			}
		});
	}
	


    /**
     * @param url      下载链接
     * @param filePath 下载保存文件夹
     * @param fileName 下载文件名
     */
    public void download(final String url, final String fileRootPath, final String fileName, final DownloadCallBack downloadCallBack) {

        Request request = new Request.Builder().url(url).tag(url).build();
        Call call = mOkHttpClient.newCall(request);
        mCallList.add(call);
        call.enqueue(new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {
            	
            	int code = response.code();
            	if(code != 200){
            		if (downloadCallBack != null) {
                        downloadCallBack.onFilure(response.message());
                    }
            		return;
            	}
            	
                InputStream inputStream = response.body().byteStream();

                if (inputStream != null) {

                    long fileLength = response.body().contentLength();
                    if (downloadCallBack != null) {
                        downloadCallBack.onStart(fileLength);
                    }

                    try {
                        File rootFile = new File(fileRootPath);

                        if (!rootFile.exists() || !rootFile.isDirectory()) {
                            rootFile.mkdirs();
                        }

                        File tempFile = new File(rootFile.getAbsolutePath() + File.separator + fileName);

                        if (tempFile.exists()) {
                            tempFile.delete();
                        }

                        tempFile.createNewFile();

                        // 已读出流作为参数创建一个带有缓冲的输出流
                        BufferedInputStream bis = new BufferedInputStream(inputStream);

                        // 创建一个新的写入流,讲读取到的图像数据写入到文件中
                        FileOutputStream fos = new FileOutputStream(tempFile);
                        // 已写入流作为参数创建一个带有缓冲的写入流
                        BufferedOutputStream bos = new BufferedOutputStream(fos);

                        int read;
                        int count = 0;

                        byte[] buffer = new byte[1024];
                        while ((read = bis.read(buffer)) != -1) {
                            bos.write(buffer, 0, read);
                            count += read;
                            if (downloadCallBack != null) {
                                downloadCallBack.onGoing(fileLength, count);
                            }

                        }
                        bos.flush();
                        bos.close();
                        fos.flush();
                        fos.close();
                        inputStream.close();
                        bis.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (downloadCallBack != null) {
                            downloadCallBack.onFilure(e.toString());
                        }
                    }
                } else {
                    if (downloadCallBack != null) {
                        downloadCallBack.onFilure("无法找到该资源");
                    }
                }
            }

            @Override
            public void onFailure(Call call, IOException ex) {
                if (downloadCallBack != null) {
                    downloadCallBack.onFilure(ex.toString());
                }
            }
        });
    }

    /**
     * 下载状态回调
     */
    public interface DownloadCallBack {
        /**
         * 开始下载(获取文件成功)
         *
         * @param fileLength 文件长度
         */
        public void onStart(long fileLength);

        /**
         * 下载中(将文件保存到本地)
         *
         * @param fileLength 文件长度
         * @param progress   已下载长度
         */
        public void onGoing(long fileLength, long downloadLength);

        /**
         * 下载失败
         *
         * @param errorException 错误原因
         */
        public void onFilure(String exception);
    }
}

三、OkHttp的入门解析

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值