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;
}
}
PostJsonModel.java
调用、回调【跟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;
}
}
UploadFilesModel.java
调用
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;
}
okhttputils【 Android 一个改善的okHttp封装库】使用(二)的更多相关文章
- okhttputils【 Android 一个改善的okHttp封装库】使用(一)
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 本文使用的OKHttp封装库是张鸿洋(鸿神)写的,因为在项目中一直使用这个库,所以对于一些常用的请求方式都验证过,所以特此整理下. ...
- okhttputils【 Android 一个改善的okHttp封装库】使用(三)
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 这一篇主要讲一下将OkHttpUtils运用到mvp模式中. 数据请求地址:http://www.wanandroid.com/to ...
- Android 一个改善的okHttp封装库
膜拜一下~ 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/49734867: 本文出自:[张鸿洋的博客] 一.概述 之前写了篇A ...
- Android 一个改进的okHttp封装库
一.概述 之前写了篇Android OkHttp完全解析 是时候来了解OkHttp了,其实主要是作为okhttp的普及文章,当然里面也简单封装了工具类,没想到关注和使用的人还挺多的,由于这股热情,该工 ...
- 一个高性能异步socket封装库的实现思路 (c#)
前言 socket是软件之间通讯最常用的一种方式.c#实现socket通讯有很多中方法,其中效率最高就是异步通讯. 异步通讯实际是利用windows完成端口(IOCP)来处理的,关于完成端口实现原理, ...
- Android一个包含表格的图标库
之前有写过一个图表lib,但是开发的速度,大多很难跟上产品需求变化的脚步,所以修改了下原先的图表库,支持图表下面能整合table显示对应的类目,用曲线替换了折线,支持多曲线的显示,增加了显示的动画,, ...
- 从零开始构建一个Reactor模式的网络库(二)线程类Thread
线程类Thread是对POSIX线程的封装类,因为要构建的是一个Linux环境下的多线程网络库,对线程的封装是很必要的. 首先是CurrentThread命名空间,主要是获取以及缓存线程id: #if ...
- 打造属于自己的Altium Designer 3D封装库,不需要懂专门的三维设计软件
看到Andy_2020发的帖子“Altium Designer专题”之后,对Altium Designer的3D功能很感兴趣,着手自己做一个AD的3D封装库.刚开始按照Andy介绍的方法,学了两天So ...
- Android 设计模式实战之关于封装计费代码库的策略模式详谈
写在之前 这周生活上出现了很多的不如意,从周一开始就觉得哪里出现了问题,然后就是各种烦躁的情绪,后来事情还真是如预感的那样发生了,很是心痛,但也无可奈何,希望大家都好好珍惜自己身边的人:友人,亲人,家 ...
随机推荐
- Python实现控制台密码星号输入
import msvcrt, sys, os print('password: ', end='', flush=True) li = [] while 1: ch = msvcrt.getch() ...
- Firefox Profile
win7环境下打开Firefox,跳出提示信息 "无法加载你的firefox配置文件 它可能已经丢失或无法访问" 解决方法: 1.按下WIN+R 调出运行,然后输入: firefo ...
- in_flight_pqueue.go
// right child } if (*pq)[j].pri >= (*pq)[i].pri { break } ...
- nsq源码阅读笔记之nsqd(一)——nsqd的配置解析和初始化
配置解析 nsqd的主函数位于apps/nsqd.go中的main函数 首先main函数调用nsqFlagset和Parse进行命令行参数集初始化, 然后判断version参数是否存在,若存在,则打印 ...
- Hibernate Annotation _List/Map
// Student.java 实体类 package com.tao.pojo; import java.util.List; public class Student { private int ...
- Centos打开、关闭、结束tomcat,及查看tomcat运行日志
cd到tomcat目录下之后 启动:一般是执行sh bin/startup.sh 停止:一般是执行sh bin/shutdown.sh查看:执行ps -ef |grep tomcat 输出如下 *** ...
- aes 128、192、256位,cbc、cfb、ecb、ofb、pcbc加密解密
AES加解密总共有以下这些 算法/模式/填充 字节加密后数据长度 不满16字节加密后长度 AES/CBC/NoPadding 16 不支持 AES/CBC/PKCS5Padding 32 16 AES ...
- (6)STM32使用HAL库实现modbus的简单通讯
1.判断地址.校验 2.读取本机数据并校验打包 3.发送数据包 4.本机数据长度比要读取的长度短怎么办 4.校验错误怎么办
- springboot2.x里面访问静态资源的坑
在spring boot的自定义配置类继承 WebMvcConfigurationSupport 后,发现自动配置的静态资源路径( classpath:/META/resources/,classpa ...
- AWVS12 介绍和安装详解 -- For Windows10
一.AWVS介绍: Acunetix Web Vulnerability Scanner,简称:AWVS,是一个自动化的Web安全测试工具,它可以扫描Web站点和Web应用. AWVS可以快速扫描SQ ...