okhttp实战使用详解
来源:互联网 发布:js闪动文字 编辑:程序博客网 时间:2024/06/04 22:47
我是把okhttp封装起来了,然后调用了,下面我直接把代码粘贴出来,直接用就可以了。
首先我把这个封装的东西放在一个单独的包里。
再看看里面写的都是什么吧
/** * Created by yzx on 2017/7/1 */public class CancelAble { Call call; public void cancel(){ if(call != null){ call.cancel(); call = null; } }}
/** * 封装的okhttp 2017/7/1 */public class OKClient { private final OkHttpClient client; private final Handler mHandler = new Handler(Looper.getMainLooper()); private final ArrayList<WeakReference<CancelAble>> callList = new ArrayList<>(0); public OKClient(OkHttpClient client){ this.client = client; } /*=================== method======================*/ public CancelAble get(String url , RequestParam params , OKRequestCallback callback){ cleanCancelAbleList(); String queryString = params == null?"":params.getQueryString(); Request request = new Request.Builder().url(url+queryString).get().build(); CancelAble cancelAble = new CancelAble(); cancelAble.call = client.newCall(request); callList.add(new WeakReference<>(cancelAble)); execCallback(cancelAble.call,callback); return cancelAble; } public CancelAble post(String url,RequestParam params , OKRequestCallback callback){ cleanCancelAbleList(); Request request = (params != null && params.hasFile()) ? getFilePostRequest(url,params) : getStringPostRequest(url,params); CancelAble cancelAble = new CancelAble(); cancelAble.call = client.newCall(request); callList.add(new WeakReference<>(cancelAble)); execCallback(cancelAble.call , callback); return cancelAble; } public CancelAble download(String url ,final File targetFile , boolean goon,final OKDownLoadCallback callback){ cleanCancelAbleList(); String rangeHeaderValue = null; if(goon && Util.isFileUseful(targetFile)){ rangeHeaderValue = "bytes="+targetFile.length()+"-"; } else { targetFile.delete(); goon = false; } final long hasDownLen = goon ? targetFile.length() : 0; Request.Builder builder = new Request.Builder().url(url).get(); if(goon) builder.addHeader("Range", rangeHeaderValue); CancelAble cancelAble = new CancelAble(); cancelAble.call = client.newCall(builder.build()); callList.add(new WeakReference<>(cancelAble)); cancelAble.call.enqueue(new Callback() { public void onResponse(Call call, Response response) throws IOException { if(call.isCanceled()) return ; if(response.isSuccessful()){ long total; try{ total = Long.parseLong(response.header("Content-Length")); } catch (Exception e){ total = 0; } BufferedInputStream in = new BufferedInputStream(response.body().byteStream()); byte[] buffer = new byte[1024*8]; long hasWriteLen = hasDownLen; int len; RandomAccessFile out = new RandomAccessFile(targetFile, "rwd"); out.skipBytes((int)hasWriteLen); long lastPublishTime = System.currentTimeMillis() - 334; while((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); hasWriteLen += len; long now; if((now = System.currentTimeMillis()) - lastPublishTime > 333){ publishProgress(callback,total,hasWriteLen); lastPublishTime = now; } } publishProgress(callback,total,total); in.close(); out.close(); mHandler.post(new Runnable() { public void run() { callback.onComplete(targetFile); } }); }else mHandler.post(new Runnable() { public void run() { callback.onError(OKDownLoadCallback.ERROR_NET); } }); } public void onFailure(Call call, IOException e) { if(call.isCanceled()) return ; mHandler.post(new Runnable() { public void run() { callback.onError(OKDownLoadCallback.ERROR_SDCARD); } }); } }); return cancelAble; } public void cancelAll(){ for (WeakReference<CancelAble> item : callList) if(item.get()!=null) item.get().cancel(); callList.clear(); } /*=================== internal======================*/ private void publishProgress(final OKDownLoadCallback callback, final long total , final long current){ mHandler.post(new Runnable() { public void run() { try{ int p = (int)(1000 * current / total); callback.onProgress(p >1000 ? 1000 : (p <0 ? 0 : p)); } catch(Exception e){ callback.onProgress(1000); } } }); } private void cleanCancelAbleList(){ if(callList.size() <= client.dispatcher().getMaxRequests()) return ; ArrayList<WeakReference> readyRemoveList = new ArrayList<>(callList.size()); for (WeakReference<CancelAble> item : callList) if(item.get() == null) readyRemoveList.add(item); callList.removeAll(readyRemoveList); } private Request getFilePostRequest(String url,RequestParam params){ final MultipartBody.Builder builder = new MultipartBody.Builder("ook------------------------------------------ook").setType(MultipartBody.FORM); params.iteratorString(new RequestParam.KeyValueIteratorListener() { public void onIterator(String key, String value) { builder.addFormDataPart(key,value); } }); params.iteratorFile(new RequestParam.KeyFileIteratorListener() { public void onIterator(String key, File file) { builder.addFormDataPart(key,file.getName(), RequestBody.create(MediaType.parse("application/octet-stream") , file)); } }); return new Request.Builder().url(url).post(builder.build()).build(); } private Request getStringPostRequest(String url,RequestParam params){ final FormBody.Builder builder = new FormBody.Builder(); if(params != null) params.iteratorString(new RequestParam.KeyValueIteratorListener() { public void onIterator(String key, String value) { builder.add(key,value); } }); return new Request.Builder().url(url).post(builder.build()).build(); } private void execCallback(Call call,final OKRequestCallback callback){ call.enqueue(new Callback() { public void onResponse(Call call, Response response) throws IOException { if(callback == null) return ; if(call.isCanceled()) return ; final boolean isSuccess = response.isSuccessful(); final String bodyString = response.body().string(); final int code = response.code(); mHandler.post(new Runnable() { public void run() { if(isSuccess){ try { callback.onSuccess(bodyString); } catch (JSONException e) { e.printStackTrace(); } } else callback.onFailure(code); } }); } public void onFailure(Call call, IOException e) { if(callback == null) return ; if(call.isCanceled()) return ; mHandler.post(new Runnable() { public void run() { callback.onFailure(0); } }); } }); }}
/** * Created by yzx on 2016/9/1 */public interface OKDownLoadCallback { int ERROR_SDCARD = 1; int ERROR_NET = 2; void onComplete(File file); void onError(int errCode); void onProgress(int current); //0 - 1000}
package com.example.xu.hyoa.httputil;import org.json.JSONException;/** * Created by yzx on 2017/7/1 */public interface OKRequestCallback { void onSuccess(String data) throws JSONException; void onFailure(int httpCode);}
/** * Created by yzx on 2017/7/1 */public class RequestParam { private final HashMap<String,List<String>> stringMap = new HashMap<>(0); private final ArrayList<FileWrapper> fileList = new ArrayList<>(0); /** *添加string参数,key可以重复,重复则按照array参数处理 */ public void add(String key,String value){ List<String> pv = stringMap.get(key); if(pv == null) stringMap.put(key, pv = new ArrayList<>(1)); pv.add(value); } /** * 添加文件参数 */ public void addFile(String key , File file){ if(Util.isFileUseful(file)) fileList.add(new FileWrapper(file,key)); } /* ==========================internal========================== */ /* internal */ String getQueryString(){ if(stringMap.isEmpty()) return ""; final StringBuilder sb = new StringBuilder("?"); iteratorString(new KeyValueIteratorListener() { public void onIterator(String key, String value) { sb.append(key).append("=").append(value).append("&"); } }); if(sb.length() == 1) sb.deleteCharAt(0); else sb.deleteCharAt(sb.length()-1); return sb.toString(); } /* is upload file */ boolean hasFile(){ return !fileList.isEmpty(); } /* iterate string params */ void iteratorString(KeyValueIteratorListener iteratorListener){ if(iteratorListener != null && !stringMap.isEmpty()) for (Map.Entry<String, List<String>> entry : stringMap.entrySet()) for (String item : ((entry.getValue() != null) ?entry.getValue() : new ArrayList<String>(0))) iteratorListener.onIterator(entry.getKey() , item); } /* iterator file params */ void iteratorFile(KeyFileIteratorListener iteratorListener){ if(iteratorListener == null || fileList.isEmpty()) return; for (FileWrapper item : fileList) iteratorListener.onIterator(item.key,item.file); } /* ============================class============================ */ interface KeyFileIteratorListener{ void onIterator(String key, File file); } interface KeyValueIteratorListener{ void onIterator(String key, String value); } class FileWrapper{ public FileWrapper(File file,String key){this.file=file;this.key=key;} File file; String key; }}
/** * Created by yzx on 2017/7/71 */ class Util { static boolean isFileUseful(File file){ return file != null && file.exists() && file.canRead() && !file.isDirectory(); }}
到这里封装的okhttp就完事了,然后使用方法
在那个类里用 需要先声明
声明一下,把下面复制就好了。
private OKClient client = new OKClient(new OkHttpClient());
get 请求
/* get 请求 */ //url *****这是请求接口 public void get(View view){ RequestParam param = new RequestParam(); param.add("fuck","fuck1"); param.add("fuck","fuck2");//这是参数 /* 这个CancelAble对象, 可以实现本次请求的取消 -> cancelAble.cancel() */ CancelAble cancelAble = client.get(url, param, new OKRequestCallback() { public void onSuccess(String data) { Log.e("data",data); } public void onFailure(int httpCode) { Toast.makeText(MainActivity.this, "" + httpCode, Toast.LENGTH_SHORT).show(); } }); }
post 请求
/* post 请求 */ public void post(View view){ RequestParam param = new RequestParam(); param.add("pjlx","0");//岗位id CancelAble cancelAble = client.post(sds, param, new OKRequestCallback() { public void onSuccess(String data) { Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show(); Log.e("data",data); } public void onFailure(int httpCode) { Toast.makeText(MainActivity.this, "" + httpCode+"", Toast.LENGTH_SHORT).show(); Log.e("httpCode"," "+httpCode); } }); }
上传文件
/** * 上传文件 * */ public void postFile(View view){ RequestParam param = new RequestParam(); File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/a.jpg"); param.addFile("fileOptions.file",file); Log.e("aaa",file.toString()+""); Log.e("ddd",file.exists()+""); CancelAble cancelAble = client.post(url, param, new OKRequestCallback() { public void onSuccess(String data) { Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show(); Log.e("data",data); } public void onFailure(int httpCode) { Log.e("httpCode",""+httpCode); Toast.makeText(MainActivity.this, httpCode+"", Toast.LENGTH_SHORT).show(); } }); }
下载
/* 下载 */ public void download(View view){ final TextView tv = (TextView) view; String ren ="yumi"; String url = "http://pic.qiantucdn.com/58pic/19/94/04/91U58PICT89_1024.jpg"; File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ren+".jpg"); while(file.exists()){ i++; ren="yumi"+"("+i+")"; file=null; file=new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ren+".jpg"); } client.download(url, file , true /* 这个参数表示是否断线续传 */ , new OKDownLoadCallback() { public void onComplete(File file) { Toast.makeText(MainActivity.this, "over", Toast.LENGTH_SHORT).show(); } public void onError(int errCode) { Toast.makeText(MainActivity.this, "error : "+ errCode , Toast.LENGTH_SHORT).show(); } public void onProgress(int current) { tv.setText(current+""); } }); }
以上汇报完毕,你最好包不要复制,不然会出错。
阅读全文
0 0
- okhttp实战使用详解
- OkHttp使用详解
- Okhttp使用详解
- OkHttp的使用详解
- OkHttp使用详解
- OkHttp使用详解
- OkHttp使用详解
- Okhttp使用详解
- OkHttp使用详解一
- OKHttp使用详解
- OkHttp使用详解
- okhttp使用详解和原理
- okhttp的使用及详解
- (4.2.36.1)HTTP之OkHttp(一): Okhttp使用详解
- android http——OkHttp使用详解
- OkHttp使用详解——完全版
- OKHttp使用详解及源码解析
- OkHttp的封装和使用详解
- CUDA编程(九)并行矩阵乘法
- ionic 环境搭建之marc
- 说说JSON和JSONP,也许你会豁然开朗,含jQuery用例
- bugku ctf Reverse 逆向入门 writeup
- 关于python-web开发中分页的处理
- okhttp实战使用详解
- Android-scrollview嵌套listview、webview、gridview不置顶问题
- 关于使用ueditor的小积累
- python3发送smtp邮件
- caffe的简单python脚本
- 自定义ImageView点击实现两张图片切换
- 使用redis文件服务器完成图片下载显示
- 一次sqlserver变慢优化过程
- angular2 引用bootstrap-daterangepicker