版权声明:本文为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封装库】使用(二)的更多相关文章

  1. okhttputils【 Android 一个改善的okHttp封装库】使用(一)

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 本文使用的OKHttp封装库是张鸿洋(鸿神)写的,因为在项目中一直使用这个库,所以对于一些常用的请求方式都验证过,所以特此整理下. ...

  2. okhttputils【 Android 一个改善的okHttp封装库】使用(三)

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 这一篇主要讲一下将OkHttpUtils运用到mvp模式中. 数据请求地址:http://www.wanandroid.com/to ...

  3. Android 一个改善的okHttp封装库

    膜拜一下~ 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/49734867: 本文出自:[张鸿洋的博客] 一.概述 之前写了篇A ...

  4. Android 一个改进的okHttp封装库

    一.概述 之前写了篇Android OkHttp完全解析 是时候来了解OkHttp了,其实主要是作为okhttp的普及文章,当然里面也简单封装了工具类,没想到关注和使用的人还挺多的,由于这股热情,该工 ...

  5. 一个高性能异步socket封装库的实现思路 (c#)

    前言 socket是软件之间通讯最常用的一种方式.c#实现socket通讯有很多中方法,其中效率最高就是异步通讯. 异步通讯实际是利用windows完成端口(IOCP)来处理的,关于完成端口实现原理, ...

  6. Android一个包含表格的图标库

    之前有写过一个图表lib,但是开发的速度,大多很难跟上产品需求变化的脚步,所以修改了下原先的图表库,支持图表下面能整合table显示对应的类目,用曲线替换了折线,支持多曲线的显示,增加了显示的动画,, ...

  7. 从零开始构建一个Reactor模式的网络库(二)线程类Thread

    线程类Thread是对POSIX线程的封装类,因为要构建的是一个Linux环境下的多线程网络库,对线程的封装是很必要的. 首先是CurrentThread命名空间,主要是获取以及缓存线程id: #if ...

  8. 打造属于自己的Altium Designer 3D封装库,不需要懂专门的三维设计软件

    看到Andy_2020发的帖子“Altium Designer专题”之后,对Altium Designer的3D功能很感兴趣,着手自己做一个AD的3D封装库.刚开始按照Andy介绍的方法,学了两天So ...

  9. Android 设计模式实战之关于封装计费代码库的策略模式详谈

    写在之前 这周生活上出现了很多的不如意,从周一开始就觉得哪里出现了问题,然后就是各种烦躁的情绪,后来事情还真是如预感的那样发生了,很是心痛,但也无可奈何,希望大家都好好珍惜自己身边的人:友人,亲人,家 ...

随机推荐

  1. 通过pycharm的Database设置进行数据库的可视化

    pycharm是一个很好的IDE,它还有一个功能直接通过这个IDE连接数据库,然后对数据库进行相关的操作,这样我们可以不用navicat for mysql这样的可视化工具了.   输入账号密码数据库 ...

  2. MySQL数据库简识

    MySQL:关系型数据库      (由瑞典MySQL AB公司开发,后来被Sun公司收购,Sun公司后来又被Oracle公司收购,目前属于Oracle旗下产品)         开源 免费 不要钱 ...

  3. Python爬虫三年没入门,传授一下绝世神功,经理唏嘘不已!

    长期枯燥的生活,敲代码的时间三天两头往吸烟室跑,被项目经理抓去训话. "入门"是学习Python最重要的阶段,虽然这个过程也许会非常缓慢.当你心里有一个目标时,那么你学习起来就不会 ...

  4. http_server.go

    , fmt.Sprintf("%s: closing %s", proto, listener.Addr())) }

  5. JS基础:常用API

    全局属性 typeof() 检测数据类型 parseInt() 从字符串解析一个整数 parseFloat() 从字符串解析一个小数 Number() 强制类型转换为数字 String() 强制类型转 ...

  6. Python3字符串替换replace(),translate(),re.sub()

    Python3的字符串替换,这里总结了三个函数,replace()和translate()和re.sub() replace() replace() 方法把字符串中的 old(旧字符串) 替换成 ne ...

  7. 【爆料】-《布莱顿大学毕业证书》Brighton一模一样原件

    布莱顿大学毕业证[微/Q:2544033233◆WeChat:CC6669834]UC毕业证书/联系人Alice[查看点击百度快照查看][留信网学历认证&博士&硕士&海归&am ...

  8. OsharpNS轻量级.net core快速开发框架简明入门教程-基于Osharp实现自己的业务功能

    OsharpNS轻量级.net core快速开发框架简明入门教程 教程目录 从零开始启动Osharp 1.1. 使用OsharpNS项目模板创建项目 1.2. 配置数据库连接串并启动项目 1.3. O ...

  9. java爬虫,爬取当当网数据

     背景:女票快毕业了(没错!我是有女票的!!!),写论文,主题是儿童性教育,查看儿童性教育绘本数据死活找不到,没办法,就去当当网查询下数据,但是数据怎么弄下来呢,首先想到用Python,但是不会!!百 ...

  10. MySQL 复制 - 性能与扩展性的基石 2:部署及其配置

    正所谓理论造航母,现实小帆船.单有理论,不动手实践,学到的知识犹如空中楼阁.接下来,我们一起来看下如何一步步进行 MySQL Replication 的配置. 为 MySQL 服务器配置复制非常简单. ...