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() {@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {sendFailCallback(callBack, e.toString());}@Overridepublic 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() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});OkHttpClient  httpClient = builder1.build();Call call = httpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});OkHttpClient  httpClient = builder1.build();Call call = httpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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() {@Overridepublic 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() {@Overridepublic 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 {@Overridepublic void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic 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 {@Overridepublic 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() {@Overridepublic void onFileDownLoad(int progress) {}@Overridepublic void downLoadFinish() {}@Overridepublic 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() {@Overridepublic void onFileDownLoad(int progress) {}@Overridepublic void downLoadFinish() {}@Overridepublic void finishDown(File file) {Uri uri = Uri.fromFile(file);context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));}});}return "1";}

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

  1. 26.Android 下载图片保存到相册

    26.Android 下载图片保存到相册 Android 下载图片保存到相册 前言 实现思路 自定义Dialog 自定义Handler 自定义AsyncTask AndroidManifest配置权限 ...

  2. android图片保存形式,Android应用开发之Android ScrollView截图和图片保存到相册的方式...

    本文将带你了解Android应用开发之Android ScrollView截图和图片保存到相册的方式,希望本文对大家学Android有所帮助. 1.1首先来看你一种截取屏幕,这种代码有缺陷,只能截取一 ...

  3. 小程序权限设置:小程序下载图片保存到相册拒绝权限后,再次打开权限的解决方案

    小程序下载图片保存到相册功能,首次操作会提示:保存图片或视频到你的相册,有'拒绝'和'允许'两个选项,如果选择了拒绝就会保存失败:saveImageToPhotosAlbum:fail auth de ...

  4. 抖音实战~分享模块~短视频下载(保存到相册)

    文章目录 一.可见范围 1. 自己发布短视频 2. 其他人发布短视频 二.源码分析 2.1. 底部窗口popup 2.2. 实现组件uni-popup 弹出层 2.3. 插件涉及组件 2.4. 组件改 ...

  5. android 相册view,Android直接把当前View保存到相册

    最近做一个需求,就是把点击一个商品,弹出一个dialog,然后点击保存,把这个dialog保存到相册,一开始了解这个需求,当时想的就是调用系统的截屏,但是考虑到截屏了那多出来的部分不是还得去手动裁剪, ...

  6. Android 电子签名/手写签名 保存到相册详解

    ps:因公司推崇线上信息办公化 设计到客户签名 将客户签好的名字上传到服务器 因此 写了一个demo 废话不多哔哔 上效果图: 这里我运用的是自定义view //权限<uses-permissi ...

  7. 考拉解析网站Android 安卓手机下载视频到手机相册

    第一步:打开网站http://www.zanqianba.com并粘贴视频链接进输入框 第二步:点击下载视频链接

  8. Android 下载网络图片保存到相册

    下载类,可以url下载到相册,记得在清单加权限,6.0代码动态加权限判断,下载图片要在子线程中下载,下载完后广播更新相册 在清单文件里面添加权限: <!--网络--><uses-pe ...

  9. Android下载网络图片并保存到相册

    下载类,可以url下载到相册,记得在清单加权限,6.0代码动态加权限判断,下载图片要在子线程中下载,下载完后广播更新相册 在清单文件里面添加权限: <!--网络--><uses-pe ...

最新文章

  1. 推荐一位在BAT大厂工作的技术+美女双料博主
  2. MyBatis之ResultMap标签
  3. Maven如何用Eclipse创建一个Maven项目【笔记自用】
  4. Ubuntu 12.04软件源、更新源
  5. hibernate级联保存问题
  6. TensorFlow神经网络(五)输入手写数字图片进行识别
  7. 自己写的一个执行带参数的sql,PreparedStatement
  8. 机器学习 python 库_Python机器学习库
  9. 通过方法将汉字转成拼音
  10. 630显卡驱动安装win7_Centos7 显卡驱动安装教程
  11. 《Puppet权威指南》——第1章 运维工程师的利器——自动化运维工具
  12. GRE_××× 配置(建议选择Cisco2811路由器)
  13. Masscan:最快的互联网IP端口扫描器
  14. 微信开放平台授权登录详细流程-第三方登录
  15. 关于数据库、数据治理、AIOps的这些痛点,你需要知道! | DAMS 2020
  16. 纪念三毛辞世20周年——《三毛经典语录》
  17. metasequoia :Summoner
  18. 汉字动图动态图gif格式,无水印 4500个汉字
  19. RTThread从底层AT组件到上层SAL之间的关系
  20. Nodejs学习路线图

热门文章

  1. C#中悲观锁和乐观锁
  2. matlab 显示高光谱,高光谱图像显示问题
  3. 什么是前端框架与后端框架
  4. 深入理解volatile关键字---缓存一致性原理
  5. http网页返回状态码含义
  6. 虚拟机WindowServer2003共享文件夹
  7. redis客户端工具下载,RedisDesktopManager,RedisInsight
  8. JavaScript的内存管理
  9. 生物统计学(biostatistics)学习笔记(二)
  10. 2020年总结:平安辞旧岁,老牛自奋蹄!