okhttputils【 Android 一个改善的okHttp封装库】使用(二)
版权声明:本文为HaiyuKing原创文章,转载请注明出处!
上一篇讲了如何在项目中导入OKHttputils库的操作,这一篇主要讲常见请求的写法。
get请求
public String getPersionTypeApi(StringCallback callback) throws Exception { String result = ""; OkHttpUtils .get() .url(getSpcyUrl(ServerApi.GET_PERSION_TYPE_URL)) .addParams("IS_JSON", "true") .addParams("VALUE_OBJES_4_JSON", "jsonMap") .id(100) .tag(context) .build() .execute(callback); return result; }
调用
private void getPersionType(){ try { LoginLogic.Instance(MainActivity.this).getPersionTypeApi(new GetPersionTypeStringCallback()); } catch (Exception e) { e.printStackTrace(); } }
回调
public class GetPersionTypeStringCallback extends StringCallback { @Override public void onBefore(Request request, int id) {//showProgressDialog("");//显示进度加载框 } @Override public void onAfter(int id) {//dismissProgressDialog();//隐藏进度加载框 } @Override public void onError(Call call, Exception e, int id) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_again)); Log.w(TAG,"{onError}e="+e.toString()); } @Override public void onResponse(String response, int id) { Log.e(TAG, "onResponse:response="+response); switch (id) { case 100://http try { if (response != null && !"".equals(response)){ //解析 } else { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_null_exception)); } } catch (JSONException e) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception)); }catch (Exception e) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception)); } finally { } break; case 101://https break; } } @Override public void inProgress(float progress, long total, int id) { Log.e(TAG, "inProgress:" + progress); } }
Post请求
public String LoginApi(String userName, String password,StringCallback callback) throws Exception { String result = ""; OkHttpUtils .post() .url(getSpcyUrl(ServerApi.LOGIN_URL)) .addParams("user.userName", userName) .addParams("user.password", password) .addParams("IS_JSON", "true") .addParams("loginModel", "mobile") .addParams("VALUE_OBJES_4_JSON", "loginUser") .addParams("userLoginModel", "mobile") .id(100) .tag(context) .build() .execute(callback); return result; }
调用
private void Login(){ String userName = "xxx"; String passWord = "sssxxxccccvvfddfggfgfg"; try { LoginLogic.Instance(MainActivity.this).LoginApi(userName, passWord, new LoginStringCallback()); } catch (Exception e) { e.printStackTrace(); } }
回调
public class LoginStringCallback extends StringCallback { @Override public void onBefore(Request request, int id) {//showProgressDialog("");//显示进度加载框 } @Override public void onAfter(int id) {//dismissProgressDialog();//隐藏进度加载框 } @Override public void onError(Call call, Exception e, int id) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_again)); Log.w(TAG,"{onError}e="+e.toString()); } @Override public void onResponse(String response, int id) { Log.e(TAG, "onResponse:response="+response); switch (id) { case 100://http try { if (response != null && !"".equals(response)){ //解析登录成功信息 JSONObject responseObj = new JSONObject(response); } else { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_null_exception)); } } catch (JSONException e) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception)); }catch (Exception e) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception)); } finally { } break; case 101://https break; } } @Override public void inProgress(float progress, long total, int id) { Log.e(TAG, "inProgress:" + progress); } }
postString【Json数据】请求
public String postJsonApi(PostJsonModel postJsonModel, StringCallback callback){ String result = ""; OkHttpUtils .postString() .url(getSpcyUrl(ServerApi.POSTJSON_URL)) .content(new Gson().toJson(postJsonModel)) .mediaType(MediaType.parse("application/json; charset=utf-8")) .id(100) .tag(context) .build() .execute(callback); return result; }
package com.why.project.okhttputilsdemo.model; /** * Created by HaiyuKing * Used */ public class PostJsonModel { private String title = ""; private String tic = ""; private String type = ""; public String getTic() { return tic; } public void setTic(String tic) { this.tic = tic; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
调用、回调【跟post、get请求的回调写法类似】
post提交文件请求
public String postFileApi(File file, StringCallback callback){ String result = ""; OkHttpUtils .postFile() .url(getSpcyUrl(ServerApi.POSTFILE_URL)) .file(file) .id(100) .tag(context) .build() .execute(callback); return result; }
调用、回调【跟post、get请求的回调写法类似】
上传单个文件请求
/** * 单个文件上传接口 */ public String upLoadFileApi(String checktaskId, String clauseId, String checkClauseId, String filepath, String filename,StringCallback callback){ String result = ""; OkHttpUtils .post() .url(getSpcyUrl(ServerApi.UPLOAD_FILE_URL)) .addFile("uploadUtil.file", filename, new File(filepath)) .addParams("jcCheckTaskId", checktaskId) .addParams("clId", clauseId) .addParams("uploadUtil.checkClauseId", checkClauseId) .id(100) .tag(context) .build() .execute(callback); return result; }
调用
private void upLoadFile(String filePath, String fileName){ String checktaskId = "402881ca5d2b3f5c015d2b40da3a0002"; String clauseId = "402881ca5d2b3f5c015d2b40dec30216"; String checkClauseId = "40288188587234fe015872e256a300ab"; LoginLogic.Instance(MainActivity.this).upLoadFileApi(checktaskId, clauseId, checkClauseId, filePath, fileName, new UpLoadFileStringCallback()); }
回调
public class UpLoadFileStringCallback extends StringCallback { public UpLoadFileStringCallback(){ } @Override public void onBefore(Request request, int id) {//showProgressDialogUpload("");//显示加载对话框 } @Override public void onAfter(int id) {//dismissProgressDialog();//隐藏进度加载框 } @Override public void onError(Call call, Exception e, int id) {ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_again)); } @Override public void onResponse(String response, int id) { Log.e(TAG, "onResponse:response="+response); switch (id) { case 100://http try { if (response != null && !"".equals(response)){ // JSONObject object = new JSONObject(response); if(object.has("result") && object.getString("result").equals("上传成功")){ ToastUtil.showShortToastCenter("上传成功"); }else{ ToastUtil.showShortToastCenter("上传失败,请重试!"); } } else { ToastUtil.showShortToastCenter("上传失败,请重试!"); } }catch (JSONException e) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception)); }catch (Exception e) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception)); } finally { } break; case 101://https break; } } @Override public void inProgress(float progress, long total, int id) { Log.e(TAG, "inProgress:" + progress);//inProgress:0.99884826 tv_result.setText("正在上传:" + (int)(progress * 100)+"%");//模拟显示进度值 //ProgressWheelDialogUtil.setDialogMsg((int)(progress * 100)+"%");//更改上传进度提示框的进度值 } }
上传多个文件的请求
/** * 多个文件上传接口 */ public String upLoadFilesApi(String checktaskId, String clauseId, String checkClauseId, List<UploadFilesModel> uploadFilesModelList, StringCallback callback){ String result = ""; HashMap<String, File> fileMap = new HashMap<String,File>(); for(int i=0;i<uploadFilesModelList.size();i++) { UploadFilesModel model = uploadFilesModelList.get(i); File file = new File(model.getFilePath()); fileMap.put(model.getFileName(), file); } OkHttpUtils .post() .url(getSpcyUrl(ServerApi.UPLOAD_FILE_URL)) .files("uploadUtil.file",fileMap) .addParams("jcCheckTaskId", checktaskId) .addParams("clId", clauseId) .addParams("uploadUtil.checkClauseId", checkClauseId) .id(100) .tag(context) .build() .execute(callback); return result; }
package com.why.project.okhttputilsdemo.model; /** * Created by HaiyuKing * Used 上传多个文件的model类 */ public class UploadFilesModel { private String filePath; private String fileName; public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } }
调用
private void upLoadFiles(List<UploadFilesModel> uploadFilesModelList){ String checktaskId = "402881ca5d2b3f5c015d2b40da3a0002"; String clauseId = "402881ca5d2b3f5c015d2b40dec30216"; String checkClauseId = "40288188587234fe015872e256a300ab"; LoginLogic.Instance(MainActivity.this).upLoadFilesApi(checktaskId, clauseId, checkClauseId, uploadFilesModelList, new UpLoadFilesStringCallback()); }
回调
/** * 文件上传接口的自定义回调函数*/ public class UpLoadFilesStringCallback extends StringCallback { public UpLoadFilesStringCallback(){ } @Override public void onBefore(Request request, int id) {//showProgressDialogUpload("");//显示加载对话框 } @Override public void onAfter(int id) {//dismissProgressDialog();//隐藏进度加载框 } @Override public void onError(Call call, Exception e, int id) {ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_again)); } @Override public void onResponse(String response, int id) { Log.e(TAG, "onResponse:response="+response); switch (id) { case 100://http try { if (response != null && !"".equals(response)){ // JSONObject object = new JSONObject(response); if(object.has("result") && object.getString("result").equals("上传成功")){ ToastUtil.showShortToastCenter("上传成功"); }else{ ToastUtil.showShortToastCenter("上传失败,请重试!"); } } else { ToastUtil.showShortToastCenter("上传失败,请重试!"); } }catch (JSONException e) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception)); }catch (Exception e) { ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception)); } finally { } break; case 101://https break; } } @Override public void inProgress(float progress, long total, int id) { Log.e(TAG, "inProgress:" + progress);//inProgress:0.99884826 tv_result.setText("正在上传:" + (int)(progress * 100)+"%");//模拟显示进度值 //ProgressWheelDialogUtil.setDialogMsg((int)(progress * 100)+"%");//更改上传进度提示框的进度值 } }
下载文件请求【返回的下载值为文件大小】
/** * 文件下载接口【返回的下载值为文件大小】 */ public String downloadFileApi(String fileid, FileCallBack callback){ String result = ""; OkHttpUtils .get() .url(getSpcyUrl(ServerApi.DOWNLOAD_FILE_URL)) .addParams("fileid", fileid) .id(100) .tag(context) .build() .execute(callback); return result; }
调用
private void downloadFile(){ String fileSavepath = Environment.getExternalStorageDirectory().toString() + File.separator + "Download";//文件保存路径 String fileName = "download.jpg";//文件名称【应该动态获取,此处测试,所以写死即可】 String fileSize = "1.33MB";//文件大小,单位为KB、MB等【应该动态获取,此处测试,所以写死即可】 String fileid = "402881ca5d2b3f5c015d2b4466d50284"; LoginLogic.Instance(MainActivity.this).downloadFileApi(fileid, new DownLoadFileCallBack(fileSavepath, fileName,fileSize)); }
回调
/** * 文件下载接口的自定义回调函数*/ public class DownLoadFileCallBack extends FileCallBack { String fileSavepath = ""; String filename = ""; String fileSize = ""; float fileSizeNum = 0.0f; /** * @param destFileDir * @param destFileName */ public DownLoadFileCallBack(String destFileDir,String destFileName,String fileSize) { super(destFileDir, destFileName); this.fileSavepath = destFileDir; this.filename = destFileName; this.fileSize = fileSize; fileSizeNum = Float.parseFloat(fileSize.substring(0, fileSize.length() - 2)); } @Override public void onBefore(Request request, int id) {//showProgressDialogUpload("");//显示加载对话框 } @Override public void onAfter(int id) {//dismissProgressDialog();//隐藏进度加载框 } @Override public void inProgress(float progress, long total, int id) { Log.w(TAG,"{inProgress}progress="+progress);//情况一:显示下载的文件大小,单位是B -1235527.0 float progressABS = Math.abs(progress);//取正 DecimalFormat df = new DecimalFormat("#.##"); double progressKB = progressABS / 1024.0D;//获取KB值 if (fileSize.contains("MB")) progressABS = Float.parseFloat(df.format(progressKB / 1024.0D));//获取MB值 else progressABS = Float.parseFloat(df.format(progressKB)); Log.e(TAG,"progressABS:" + progressABS); Log.e(TAG,"progressABS/fileSizeNum== :" + progressABS/fileSizeNum); tv_result.setText("下载进度:" + (int)(progressABS/fileSizeNum * 100)+"%"); } @Override public void onError(Call call, Exception e, int id) { ToastUtil.showShortToast("下载失败"); } @Override public void onResponse(File file, int id) { Log.e(TAG, "onResponse :" + file.getAbsolutePath()); ToastUtil.showShortToast("下载成功"); } }
下载文件请求【返回的下载值为文件下载的比例值】
/** * 文件下载接口【返回的下载值为文件下载的比例值】 */ public String downloadFile2Api(FileCallBack callback){ String result = ""; OkHttpUtils .get() .url("http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk") .id(100) .tag(context) .build() .execute(callback); return result; }
调用
private void downloadFile2(){ String fileSavepath = Environment.getExternalStorageDirectory().toString() + File.separator + "Download";//文件保存路径 String fileName = "MobileAssistant_1.apk";//文件名称【应该动态获取,此处测试,所以写死即可】 LoginLogic.Instance(MainActivity.this).downloadFile2Api(new DownLoadFile2CallBack(fileSavepath, fileName)); }
回调
/** * 文件下载接口的自定义回调函数*/ public class DownLoadFile2CallBack extends FileCallBack { String fileSavepath = ""; String filename = ""; /** * @param destFileDir * @param destFileName */ public DownLoadFile2CallBack(String destFileDir, String destFileName) { super(destFileDir, destFileName); this.fileSavepath = destFileDir; this.filename = destFileName; } @Override public void onBefore(Request request, int id) {//showProgressDialogUpload("");//显示加载对话框 } @Override public void onAfter(int id) {//dismissProgressDialog();//隐藏进度加载框 } @Override public void inProgress(float progress, long total, int id) { Log.w(TAG,"{inProgress}progress="+progress);//情况一:下载进度值为文件的下载比例值 0.4827961 float progress1 = Math.abs(progress); tv_result.setText("下载进度:" + (int)(progress1 * 100)+"%"); } @Override public void onError(Call call, Exception e, int id) { ToastUtil.showShortToast("下载失败"); } @Override public void onResponse(File file, int id) { Log.e(TAG, "onResponse :" + file.getAbsolutePath()); ToastUtil.showShortToast("下载成功"); } }
同步请求【需要在子线程中执行】
/** * 模拟同步请求--注销*/ public String LogoutApi() throws IOException { String result = ""; //同步请求--用于在自定义的thread中执行 Response response = OkHttpUtils .post() .url(getSpcyUrl(ServerApi.LOGOUT_URL)) .addParams("IS_JSON", "true") .id(100) .tag(context) .build() .execute(); //execute方法不传入callback即为同步的请求,返回Response对象,需要自己解析 InputStream responseIs = response.body().byteStream(); BufferedReader responseBufferedReader = new BufferedReader(new InputStreamReader(responseIs, "utf-8")); StringBuilder responseStringBuilder = new StringBuilder(); while (true) { String readLine = responseBufferedReader.readLine(); if (readLine == null) { break; } responseStringBuilder.append(readLine); } responseIs.close(); result = responseStringBuilder.toString(); return result; }
调用
//模拟同步请求--注销 btn_synchronize.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { String logoutStr = LoginLogic.Instance(MainActivity.this).Logout(); Message msg = new Message(); msg.what = TOAST_SHOW; msg.obj = logoutStr; mHandler.sendMessage(msg); } catch (IOException e) { e.printStackTrace(); } } }).start(); } });
/**用于toast提示*/ private static final int TOAST_SHOW = 18; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case TOAST_SHOW: ToastUtil.showShortToast((String)msg.obj); tv_result.setText((String)msg.obj); break; } } };
单个请求添加cookie
/** * 获取接口 */ public String getNewsApi(StringCallback callback) throws Exception { String result = ""; String SESSION_SERVER_HEAD = "JSESSIONID="; String SESSION_SERVER_ID = "9B17276F7C0CA4F309ABA0C93D87A3F8"; OkHttpUtils .get() .url(getSpcyUrl(context.getString(R.string.get_news_url))) .addHeader("Cookie",SESSION_SERVER_HEAD + SESSION_SERVER_ID) .id(100) .tag(context) .build() .execute(callback); return result; }
获取cookies【用于保存到SharedPreferences中】
/**获取cookies*/ public static String getCookiesStr(){ String cookiesInfo = ""; CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient().cookieJar(); if (cookieJar instanceof CookieJarImpl) { CookieStore cookieStore = ((CookieJarImpl) cookieJar).getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for(Cookie cookie : cookies){ cookiesInfo = cookiesInfo + cookie.name() + ":" + cookie.value() + ";"; } } return cookiesInfo; }
清空cookies
/**清空cookie缓存*/ public static void clearCookies() { CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient().cookieJar(); if (cookieJar instanceof CookieJarImpl) { ((CookieJarImpl) cookieJar).getCookieStore().removeAll(); } //需要清空webview中的cookie,https://www.cnblogs.com/umpjls/p/7319177.html CookieManager webViewCookieManager = CookieManager.getInstance(); webViewCookieManager.removeAllCookie(); }
webview异步cookies
/** * Sync Cookie */ public static void syncCookie(Context context, String url){ try{ LogUtil.d("Nat: webView.syncCookie.url", url); String sessionId = ""; String loginmodel = "normal";//默认值是normal String domain = ServerApi.SERVER_URL_COOKIE;//默认值为域名(不含有http) String path = "/";//默认值为/ //获取保存的cookie信息 String savedCookie = PreferencesUtils.getString(context,PreferencesUtils.COOKEY,"");//JSESSIONID:9B17276F7C0CA4F309ABA0C93D87A3F8; LogUtil.e(TAG,"savedCookie="+savedCookie); if(!TextUtils.isEmpty(savedCookie)){ String[] cookies = savedCookie.split(";"); for(int i=0;i<cookies.length;i++){ if(!TextUtils.isEmpty(cookies[i].trim())){ if(cookies[i].trim().contains("JSESSIONID")){ String[] cookie = cookies[i].split(":"); sessionId = cookie[1].trim(); } if(cookies[i].trim().contains("loginmodel")){ String[] cookie = cookies[i].split(":"); loginmodel = cookie[1].trim(); } } } LogUtil.d(TAG, "sessionId="+sessionId); LogUtil.d(TAG, "path="+path); //方式一【没有起作用】 /*CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); cookieManager.removeSessionCookie();// 移除 cookieManager.removeAllCookie(); CookieSyncManager.getInstance().sync(); String oldCookie = cookieManager.getCookie(url); if(oldCookie != null){ LogUtil.d("Nat: webView.syncCookieOutter.oldCookie", oldCookie); } StringBuilder sbCookie = new StringBuilder(); sbCookie.append(String.format("JSESSIONID=%s",sessionId)); //ip地址的话应该是不需要设置的,只有在域名的情况下才可以设置 sbCookie.append(String.format(";domain=%s", domain)); sbCookie.append(String.format(";loginmodel=%s",loginmodel)); sbCookie.append(String.format(";path=%s",path)); String cookieValue = sbCookie.toString(); cookieManager.setCookie(url,cookieValue); LogUtil.e(TAG,"cookieValue="+cookieValue); CookieSyncManager.getInstance().sync();*/ //方式二 CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); cookieManager.removeSessionCookie();//移除 cookieManager.removeAllCookie();//移除 CookieSyncManager.getInstance().sync(); cookieManager.setCookie(url, String.format("JSESSIONID=%s",sessionId));// cookieManager.setCookie(url, String.format("Domain=%s", domain));// cookieManager.setCookie(url, String.format("Path=%s",path));// cookieManager.setCookie(url, String.format("loginmodel=%s",loginmodel));// CookieSyncManager.getInstance().sync(); String newCookie = cookieManager.getCookie(url); if(newCookie != null){ LogUtil.d("Nat: webView.syncCookie.newCookie", newCookie);// } } }catch(Exception e){ LogUtil.e("Nat: webView.syncCookie failed", e.toString()); } }
配置HTTPS请求
/** * 配置OkhttpClient */ private void initOkHttp() { CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));//修改成自带的cookie持久化,可以解决程序崩溃时返回到 //ClearableCookieJar cookieJar1 = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext())); SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new 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]; } }}, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);//设置可访问所有的https网站 OkHttpClient okHttpClient = new OkHttpClient.Builder() .connectTimeout(10000L, TimeUnit.MILLISECONDS) .readTimeout(10000L, TimeUnit.MILLISECONDS) //配置Log,通过设置拦截器实现,框架中提供了一个LoggerInterceptor,当然你可以自行实现一个Interceptor .addInterceptor(new LoggerInterceptor("TAG")) //配置持久化Cookie(包含Session) .cookieJar(cookieJar) .hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { // TODO Auto-generated method stub //return false; return true; } }) //配置Https .sslSocketFactory(sslContext.getSocketFactory()) .build(); OkHttpUtils.initClient(okHttpClient); }
设置UA【默认为okhttp/3.3】
OkHttpUtils.head().addHeader("User-Agent","mobile");//设置UA,默认为okHttp的版本okhttp/3.3.0
在MyApplication.java中的initOkHttp方法中最后一行添加。
单个请求设置超时时间
public String checkServerUrlApi(Context context,String time,StringCallback callback) throws Exception{ String result = ""; OkHttpUtils .get() .url(getSpcyUrl(context.getString(R.string.check_url))) .addParams("time", time) .id(100) .tag(context) .build() .connTimeOut(3000L) .readTimeOut(3000L) .execute(callback); return result; }