Android 网络图片,gif 下载并保存到相册

10以下,可以直接存储到非 app 目录

10及其以上,需要存到app目录,再复制到相册

下载图片是 使用 okhttp 下载的,gif 与 正常的图片都可以下载

package com.sq.lovehelper.okhttp;

import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.sq.lovehelper.MyApplication;
import com.sq.lovehelper.utils.Api;
import com.sq.lovehelper.utils.Constant;
import com.sq.lovehelper.utils.JsonUtil;
import com.sq.lovehelper.utils.SharedPreferencesUtil;
import com.sq.lovehelper.utils.StringUtil;
import com.sq.lovehelper.utils.ToastUtils;
import com.sq.lovehelper.utils.WindowUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtils {
    public static final String TAG = HttpUtils.class.getSimpleName();
    private static HttpUtils mInstance;
    private static OkHttpClient client;
    private Handler mHandler;

    private HttpUtils() {
//        File sdcache = context.getExternalCacheDir();
//        int cacheSize = 10 * 1024 * 1024;//设置缓存大小
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(new MyIntercept());


        //支持HTTPS请求,跳过证书验证
        //忽略ssl证书,android10及以上的版本就不用了
        if (Build.VERSION.SDK_INT < 29) {
            builder.sslSocketFactory(createSSLSocketFactory());
        }
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        client = builder.build();
        mHandler = new Handler(Looper.getMainLooper());
    }


    public static HttpUtils obtain() {
        if (mInstance == null) {
            synchronized (HttpUtils.class) {
                if (mInstance == null) {
                    mInstance = new HttpUtils();
                }
            }
        }
        return mInstance;
    }

    /**
     * get 普通请求
     *
     * @param url
     * @param callBack
     */
    public void get(String url, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(url)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Log.i(TAG, "onResponse: " + Thread.currentThread());
                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * get请求 传params
     *
     * @param url
     * @param params
     * @param callBack
     */
    public void get(String url, Map<String, String> params, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Log.d("KnightDuke", JsonUtil.getJsonString(params));
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(appendParams(url, params))
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Log.i(TAG, "onResponse: " + Thread.currentThread());
                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });

    }

    /**
     * get请求 传params
     *
     * @param url
     * @param params
     * @param callBack
     */
    public void getNoToken(String url, Map<String, String> params, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(appendParams(url, params))
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Log.i(TAG, "onResponse: " + Thread.currentThread());
                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });

    }


    /**
     * get请求 传heads和params
     *
     * @param url
     * @param heads
     * @param params
     * @param callBack
     */
    public void get(String url, Map<String, String> heads, Map<String, String> params, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Headers headers = appendHeaders(heads);
        Request request = new Request.Builder()
                .headers(headers)
                .url(appendParams(url, params))
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * post 普通请求
     *
     * @param url
     * @param callBack
     */
    public void post(String url, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        FormBody.Builder builder = new FormBody.Builder();
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .post(builder.build())
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * post请求 传params
     *
     * @param url
     * @param params
     * @param callBack
     */
    public void post(String url, Map<String, String> params, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        RequestBody requestBody = appendBody(params);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }


    public void postForm(String url, String jsonParams, final ICallBack callBack) {
        Log.d("KnightDuke", "request=" + jsonParams);
        if (TextUtils.isEmpty(url)) {
            return;
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .addHeader("Content-Type", "multipart/form-data")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * post请求 传heads和params
     *
     * @param url
     * @param heads
     * @param params
     * @param callBack
     */
    public void post(String url, Map<String, String> heads, Map<String, String> params, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        Headers headers = appendHeaders(heads);
        RequestBody requestBody = appendBody(params);
        Request request = new Request.Builder()
                .headers(headers)
                .post(requestBody)
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * post请求  传json数据
     *
     * @param url
     * @param jsonParams
     * @param callBack
     */
    public void post(String url, String jsonParams, final ICallBack callBack) {
        Log.d("KnightDuke", "request=" + jsonParams);
        if (TextUtils.isEmpty(url)) {
            return;
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * post请求  传json数据
     * 不带token
     *
     * @param url
     * @param jsonParams
     * @param callBack
     */
    public void postNoToken(String url, String jsonParams, final ICallBack callBack) {
        Log.d("KnightDuke", "notTokenRequest=" + jsonParams);
        if (TextUtils.isEmpty(url)) {
            return;
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * post请求  传json数据
     *
     * @param url
     * @param
     * @param callBack
     */
    public void postUrlWithParams(String url, List<String> params,String jsonParams, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        //对参数与Url 进行处理
        //1.将URl 以 - 进行分割
        //3.将分割后的数组与参数进行拼接
        String [] s = url.split("-");
        StringBuffer buffer = new StringBuffer();
        for(int i=0;i<s.length;i++){
            buffer.append(s[i]);
            if(i<params.size()){
                buffer.append(params.get(i));
            }
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(buffer.toString())
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }


    /**
     * put请求  传json数据
     *
     * @param url
     * @param jsonParams
     * @param callBack
     */
    public void put(String url, String jsonParams, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(url)
                .put(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * delete请求  传json数据
     *
     * @param url
     * @param jsonParams
     * @param callBack
     */
    public void delete(String url, String jsonParams, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonParams);
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(url)
                .delete(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * post 普通请求
     *
     * @param url
     * @param callBack
     */
    public void delete(String url, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        FormBody.Builder builder = new FormBody.Builder();
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")//添加头部
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .delete(builder.build())
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * 上传文件
     *
     * @param url
     * @param pathName
     * @param fileName
     * @param callBack
     */
    public void file(String url, String pathName, String fileName, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        MediaType MEDIA_TYPE = MediaType.parse(judgeType(pathName));
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(MEDIA_TYPE.type(), fileName,
                        RequestBody.create(MEDIA_TYPE, new File(pathName)));
        Request request = new Request.Builder()
                .header("Authorization", "Client-ID" + "9199fdef135c122")
                .url(url)
                .post(builder.build())
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * 上传文件
     *
     * @param url
     * @param file
     * @param fileName 文件全名包括后缀 例如:test.png
     * @param callBack
     */
    public void file(String url, File file, String fileName, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", fileName,
                        RequestBody.create(MediaType.parse(guessMimeType(fileName)), file));
        Request request = new Request.Builder()
                .addHeader("Content-type", "multipart/form-data")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(url)
                .post(builder.build())
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }

    /**
     * 上传文件
     *
     * @param url
     * @param
     * @param
     * @param callBack
     */
    public void files(String url, List<String> files, final ICallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);


        for (int i = 0; i < files.size(); i++) { //对文件进行遍历
            File file = new File(files.get(i)); //生成文件
            //根据文件的后缀名,获得文件类型
            builder.addFormDataPart( //给Builder添加上传的文件
                    "images[]",  //请求的名字
                    file.getName(), //文件的文字,服务器端用来解析的
                    RequestBody.create(MediaType.parse(file.getName()), file) //创建RequestBody,把上传的文件放入
            );
        }
        Request request = new Request.Builder()
                .addHeader("Content-type", "multipart/form-data")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", SharedPreferencesUtil.getData(Constant.tokenHeader, "").toString() + String.valueOf(SharedPreferencesUtil.getData(Constant.token, "")))
                .addHeader("X-API-VERSION", Api.api_v)
                .addHeader("API-VERSION", WindowUtil.getVersionCode()+"")
                .url(url)
                .post(builder.build())
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                sendFailCallback(callBack, e.toString());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                boolean isSuccessful = response.isSuccessful();
                sendSuccessCallback(callBack, isSuccessful, response);
            }
        });
    }


    /**
     * 根据文件后缀获取文件类型
     *
     * @param path
     * @return
     */
    private static String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = null;
        try {
            contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    /**
     * 根据文件路径判断MediaType
     *
     * @param pathName
     * @return
     */
    private static String judgeType(String pathName) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(pathName);
        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, final IDownLoadBack downLoadBack) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        OkHttpClient.Builder builder1 = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS);

        //支持HTTPS请求,跳过证书验证
        //忽略ssl证书,android10及以上的版本就不用了
//        if (Build.VERSION.SDK_INT < 29) {
//            builder1.sslSocketFactory(createSSLSocketFactory());
//        }
        builder1.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        OkHttpClient  httpClient = builder1.build();

        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("KnightDuke","开始下载");
                File file = new File(fileDir, fileName);
                InputStream is = null;
                FileOutputStream fos = null;
                int len = 0;
                byte[] buf = new byte[1024];
                try {
                    is = response.body().byteStream();
                    fos = new FileOutputStream(file);
                    long total = response.body().contentLength();
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载中更新进度条
                        downLoadBack.onFileDownLoad(progress);
                    }
                    fos.flush();
                    downLoadBack.downLoadFinish();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();
                }
            }
        });
    }

    /**
     * 下载文件
     *
     * @param url
     * @param fileDir
     * @param fileName
     */
    public static void downFilePic(String url, final String fileDir, final String fileName, final IDownLoadBack downLoadBack) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        OkHttpClient.Builder builder1 = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS);

        //支持HTTPS请求,跳过证书验证
        //忽略ssl证书,android10及以上的版本就不用了
//        if (Build.VERSION.SDK_INT < 29) {
//            builder1.sslSocketFactory(createSSLSocketFactory());
//        }
        builder1.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        OkHttpClient  httpClient = builder1.build();

        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("KnightDuke","开始下载");
                File file = new File(fileDir, fileName);
                InputStream is = null;
                FileOutputStream fos = null;
                int len = 0;
                byte[] buf = new byte[1024];
                try {
                    is = response.body().byteStream();
                    fos = new FileOutputStream(file);
                    long total = response.body().contentLength();
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载中更新进度条
                        downLoadBack.onFileDownLoad(progress);
                    }
                    fos.flush();

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();
                    downLoadBack.finishDown(file);
                }
            }
        });
    }

    /**
     * 请求成功
     *
     * @param callback
     * @param isSuccess
     * @param response
     */
    private void sendSuccessCallback(final ICallBack callback, final boolean isSuccess, final Response response) {
        try {
            final String responseString = response.body().string();
            final int code = response.code();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (isSuccess == true) {
                        if (code == 200 || code == 201) {
                            callback.onSuccess(responseString);
                        } else {
                            StringUtil.showErrorMessage(MyApplication.getApplication(), responseString);
                            callback.onFailure(responseString);
                        }

                    } else {
                        StringUtil.showErrorMessage(MyApplication.getApplication(), responseString);
                        callback.onFailure(responseString);
                    }

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

    /**
     * 请求失败
     *
     * @param callback
     * @param throwable
     */
    private void sendFailCallback(final ICallBack callback, final String throwable) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                // callback.onFailure(throwable);
                ToastUtils.showToastCenter(MyApplication.getApplication(), "网络异常");
            }
        });
    }

    /**
     * 将参数拼接到url上
     *
     * @param url
     * @param params
     * @return
     */
    protected String appendParams(String url, Map<String, String> params) {
        if (url == null || params == null || params.isEmpty()) {
            return url;
        }
        Uri.Builder builder = Uri.parse(url).buildUpon();
        Set<String> keys = params.keySet();
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            builder.appendQueryParameter(key, params.get(key));
        }
        return builder.build().toString();
    }

    /**
     * 增加Headers参数
     *
     * @param headers
     * @return
     */
    private Headers appendHeaders(Map<String, String> headers) {
        Headers.Builder headerBuilder = new Headers.Builder();
        if (headers == null || headers.isEmpty())
            return headerBuilder.build();

        for (String key : headers.keySet()) {
            headerBuilder.add(key, headers.get(key));
        }
        return headerBuilder.build();
    }

    /**
     * 增加post请求参数
     *
     * @param params
     * @return
     */
    private RequestBody appendBody(Map<String, String> params) {
        FormBody.Builder body = new FormBody.Builder();
        if (params == null || params.isEmpty()) {
            return body.build();
        }
        for (Map.Entry<String, String> entry : params.entrySet()) {
            body.add(entry.getKey(), entry.getValue().toString());
        }
        return body.build();
    }


    /**
     * 创建SSL
     *
     * @return
     */
    private SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return ssfFactory;
    }

    /**
     * 用于信任所有证书
     */
    class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    public interface ICallBack {
        void onFailure(String throwable);

        void onSuccess(String response);
    }

    public interface IDownLoadBack{
        void onFileDownLoad(int progress);
        void downLoadFinish();
        void finishDown(File file);
    }
}


/**
 * @author Mr.release
 * @create 2020/7/15
 * @Describe
 */

abstract class HttpCallback<Result> implements HttpUtils.ICallBack {

    @Override
    public void onSuccess(String response) {

        Class<?> cls = analysisClazzInfo(this);

        Result result = (Result) JSON.parseObject(response, cls);
        onSuccess(result);
    }

    public abstract void onSuccess(Result result);

    public static Class<?> analysisClazzInfo(Object object) {
        Type genType = object.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class<?>) params[0];
    }
}

path 为 网络图片地址  url

public static String bitmapToFileToAl(Context context, String path) {
        if (!StringUtil.isNotEmpty(path)) {
            return "";
        }

        String[] s = path.split("\\.");
        String type = "";
        if (s.length > 0) {
            type = "." + s[s.length - 1];
        } else {
            type = ".jpg";
        }
        String name = System.currentTimeMillis() + type;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            HttpUtils.obtain().downFilePic(path, Constant.picFolderPath, name, new HttpUtils.IDownLoadBack() {
                @Override
                public void onFileDownLoad(int progress) {

                }

                @Override
                public void downLoadFinish() {

                }

                @Override
                public void finishDown(File file) {
                    String mimeType = getMimeType(file);
                    String fileName = file.getName();
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.MediaColumns.DISPLAY_NAME,fileName);
                    values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
                    values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
                    ContentResolver contentResolver = context.getContentResolver();
                    Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                    if (uri == null) {
                        return;
                    }

                    try {
                        OutputStream out = contentResolver.openOutputStream(uri);
                        FileInputStream fis = new FileInputStream(file);
                        FileUtils.copy(fis, out);
                        fis.close();
                        out.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }else{
            String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "shuQuePic";
            File appDir = new File(storePath);
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            HttpUtils.obtain().downFilePic(path, storePath, name, new HttpUtils.IDownLoadBack() {
                @Override
                public void onFileDownLoad(int progress) {

                }

                @Override
                public void downLoadFinish() {

                }

                @Override
                public void finishDown(File file) {
                    Uri uri = Uri.fromFile(file);
                    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                }
            });


        }
        return "1";
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值