OkHttp封装
651 字
3 分钟
OkHttp封装

/** * 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();// }// } }); }}支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!
相关文章智能推荐
1
Android Dialog回传
Java/Android代码2018-06-21
2
AppCompatActivity的标题栏上加上返回按钮
Java笔记2018-03-25
3
Java、android彻底关闭应用方法
Java笔记2018-03-21
4
Android: runOnUiThread
Android笔记2018-03-14
5
Android隐藏标题栏代码失效
Android笔记2017-11-03
随机文章随机推荐















加载更多…