Okhttp 上傳單張、多張圖片,下載工具類
阿新 • • 發佈:2018-12-27
以下是對okhttp的封裝,希望大家不要見笑,很好用的
import android.content.Context; import android.os.Environment; import android.support.annotation.NonNull; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; /** * OKHttp3上傳工具類 */ public class OkUtils { private Context ctx; private static OkHttpClient ok = null; private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8"); private Map<String, String> map = new HashMap<String, String>();//存放 private List<String> list = new ArrayList<String>(); private static File file; private static String imgpath; private static String imageName; private OkUtils() { } ; /* *單例獲取 * */ public static OkHttpClient getInstance() { if (ok == null) { synchronized (OkUtils.class) { if (ok == null) ok = new OkHttpClient(); } } return ok; } /* * 鍵值對上傳資料 * */ public static void UploadSJ(String url, Map<String, String> map, Callback callback) { FormBody.Builder builder = new FormBody.Builder(); //遍歷map中所有的引數到builder for (String key : map.keySet()) { builder.add(key, map.get(key)); Log.e("", "key: " + key + " map.get: " + map.get(key)); } Request request = new Request.Builder() .url(url) .post(builder.build()) .build(); Call call = getInstance().newCall(request); call.enqueue(callback); } /* * 上傳一張圖片帶引數 * */ public static void UploadFileCS(String url, String key1, String path, Map<String, String> map, Callback callback) { String imagpath = path.substring(0, path.lastIndexOf("/")); String imgName[] = path.split("/"); for (int i = 0; i < imgName.length; i++) { if (i == imgName.length - 1) { String name = imgName[i]; file = new File(imagpath, name); } } MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file); //遍歷map中所有的引數到builder for (String key : map.keySet()) { builder.addFormDataPart(key, map.get(key)); } //講檔案新增到builder中 builder.addFormDataPart(key1, file.getName(), fileBody); //建立請求體 RequestBody requestBody = builder.build(); OkHttpClient okhttp = getInstance(); okhttp.newBuilder().followRedirects(true); Request request = new Request.Builder().url(url).post(requestBody).build(); Call call = getInstance().newCall(request); call.enqueue(callback); } /* *上傳多個圖片檔案 * */ @SuppressWarnings("unused") public static void UploadFileMore(String url, List<String> paths, Callback callback) { if (paths != null) { //建立檔案集合 List<File> list = new ArrayList<File>(); //遍歷整個圖片地址 for (String str : paths) { //擷取圖片地址:/storage/emulated/0 imgpath = str.substring(0, str.lastIndexOf("/")); //將圖片路徑分解成String陣列 String[] imgName = str.split("/"); for (int i = 0; i < imgName.length; i++) { if (i == imgName.length - 1) { imageName = imgName[i];//獲取圖片名稱 File file = new File(imgpath, imageName); list.add(file); } } } MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM);//設定表單型別 //遍歷圖片檔案 for (File file : list) { if (file != null) { builder.addFormDataPart("acrd", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)); } } //構建請求體 MultipartBody requestBody = builder.build(); Request request = new Request.Builder().url(url).post(requestBody).build(); Call call = getInstance().newCall(request); call.enqueue(callback); } } /* * 上傳多張圖片帶引數 * */ @SuppressWarnings("unused") public static void UploadFileSCMore(String url, String value, List<String> paths, Map<String, String> map, Callback callback) { if (paths != null && map != null) { //建立檔案集合 List<File> list = new ArrayList<File>(); //遍歷整個圖片地址 for (String str : paths) { //擷取圖片地址:/storage/emulated/0 imgpath = str.substring(0, str.lastIndexOf("/")); //將圖片路徑分解成String陣列 String[] imgName = str.split("/"); for (int i = 0; i < imgName.length; i++) { if (i == imgName.length - 1) { imageName = imgName[i];//獲取圖片名稱 File file = new File(imgpath, imageName); list.add(file); } } } MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM);//設定表單型別 //遍歷圖片檔案 for (File file : list) { if (file != null) { builder.addFormDataPart(value, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)); } } //遍歷map中所有的引數到builder for (String key : map.keySet()) { builder.addFormDataPart(key, map.get(key)); } RequestBody requestBody = builder.build(); Request request = new Request.Builder().url(url).post(requestBody).build(); Call call = getInstance().newCall(request); call.enqueue(callback); } } /** * post上傳json字串方法 * url:伺服器網址 * * @param */ public static void PostJaon(String url, String json, Callback callback) { RequestBody requestBody = RequestBody.create(JSON, json); Request build = new Request.Builder() .url(url) .patch(requestBody) .build(); Call call = getInstance().newCall(build); call.enqueue(callback); } /** * 下載檔案 * @param url 檔案網址 * @param saveDir 儲存路徑 * @param listener 回撥不用管 */ public static void download(final String url, final String saveDir, final OnDownloadListener listener) { Request request = new Request.Builder().url(url).build(); ok.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 下載失敗 listener.onDownloadFailed(); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; // 儲存下載檔案的目錄 String savePath = isExistDir(saveDir); try { is = response.body().byteStream(); long total = response.body().contentLength(); File file = new File(savePath, getNameFromUrl(url)); 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); } fos.flush(); // 下載完成 listener.onDownloadSuccess(); } catch (Exception e) { listener.onDownloadFailed(); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); } /** * @param saveDir * @return * @throws IOException * 判斷下載目錄是否存在 */ private static String isExistDir(String saveDir) throws IOException { // 下載位置 File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir); if (!downloadFile.mkdirs()) { downloadFile.createNewFile(); } String savePath = downloadFile.getAbsolutePath(); return savePath; } /** * @param url * @return * 從下載連線中解析出檔名 */ @NonNull private static String getNameFromUrl(String url) { return url.substring(url.lastIndexOf("/") + 1); } public interface OnDownloadListener { /** * 下載成功 */ void onDownloadSuccess(); /** * @param progress * 下載進度 */ void onDownloading(int progress); /** * 下載失敗 */ void onDownloadFailed(); } }