/**
 * Okhttp封装
 */
public class OkhttpNet {
    private static OkHttpClient client = null;

    private OkhttpNet() {
    }

    public static OkHttpClient getInstance() {
        if (client == null) {
            synchronized (OkhttpNet.class) {
                if (client == null)
                    client = new OkHttpClient();
            }
        }
        return client;
    }

    /**
     * Get请求
     *
     * @param url
     * @param callback
     */
    public static void doGet(String url, Callback callback) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

    /**
     * Post请求发送键值对数据
     *
     * @param url
     * @param mapParams
     * @param callback
     */
    public static void doPost(String url, Map mapParams, Callback callback) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : mapParams.keySet()) {
            builder.add(key, mapParams.get(key));
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }


    /**
     * Post请求发送JSON数据
     *
     * @param url
     * @param jsonParams
     * @param callback
     */
    public static void doPost(String url, String jsonParams, Callback callback) {
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8")
                , jsonParams);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }


    /**
     * 上传文件
     *
     * @param url
     * @param callback
     * @param map           上传文件,map值:file///文件路径
     */
    public static void doFile(String url, Map map, Callback callback) {

        //创建文件参数
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        if (map != null) {
            for (String key : map.keySet()) {

                Pattern pattern = Pattern.compile("^file///");
                    Matcher matcher = pattern.matcher(map.get(key));
                    //判断是否是要上传文件
                    if (matcher.find()) {
                        String[] path = map.get(key).split("file///");
                        String filePath = path[1];
                        String[] fileName = filePath.split("/");
                        //判断文件类型
                        MediaType MEDIA_TYPE = MediaType.parse(judgeType(filePath));
                        builder.addFormDataPart(key, fileName[fileName.length - 1],
                                RequestBody.create(MEDIA_TYPE, new File(filePath)));
                } else {
                    builder.addFormDataPart(key, map.get(key));
                }
            }
        }

        //发出请求参数
        Request request = new Request.Builder()
//                .header("Authorization", "Client-ID " + "9199fdef135c122")
                .url(url)
                .post(builder.build())
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);
    }

    /**
     * 根据文件路径判断MediaType
     *
     * @param path
     * @return
     */
    private static String judgeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }


    /**
     * 下载文件
     *
     * @param url
     * @param fileDir
     * @param fileName
     */
    public static void downFile(String url, final String fileDir, final String fileName) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(fileDir, fileName);
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();
                }
            }
            //获取进度条
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                InputStream is = null;
//                byte[] buf = new byte[2048];
//                int len = 0;
//                FileOutputStream fos = null;
//                try {
//                    is = response.body().byteStream();
//                    File file = new File(fileDir, fileName);
//                    fos = new FileOutputStream(file);
//                    //---增加的代码---
//                    //计算进度
//                    long totalSize = response.body().contentLength();
//                    long sum = 0;
//                    while ((len = is.read(buf)) != -1) {
//                        sum += len;
//                        //progress就是进度值
//                        int progress = (int) (sum * 1.0f/totalSize * 100);
//                        //---增加的代码---
//                        fos.write(buf, 0, len);
//                    }
//                    fos.flush();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } finally {
//                    if (is != null) is.close();
//                    if (fos != null) fos.close();
//                }
//            }
        });
    }
}
Last modification:October 24, 2019
如果觉得我的文章对你有用,请随意赞赏