1.依赖:
//《Okhttp网络请求依赖》 implementation 'com.squareup.okhttp3:okhttp:3.10.0' //《Gson解析依赖》 implementation 'com.google.code.gson:gson:2.8.2' //《Butterknife依赖(黄油刀)》 implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
2.权限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" tools:ignore="ProtectedPermissions" /><!--是否挂载--> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
3.封装的外层Bean
package com.example.dell.versionupdatedemo05.bean; public class MessageBean<T>{ private Boolean Success; private String msg; private T data; public Boolean getSuccess() { return Success; } public void setSuccess(Boolean success) { Success = success; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }4.封装的内层Bean
package com.example.dell.versionupdatedemo05.bean; public class VersionInfo { private int last_must_update;//需强制更新的版本 private int last_version;//需更新的版本 private String md5;//Md5码 private String url;//下载地址 public int getLast_must_update() { return last_must_update; } public void setLast_must_update(int last_must_update) { this.last_must_update = last_must_update; } public int getLast_version() { return last_version; } public void setLast_version(int last_version) { this.last_version = last_version; } public String getMd5() { return md5; } public void setMd5(String md5) { this.md5 = md5; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
5.定义成功与失败的接口
package com.example.dell.versionupdatedemo05; //定义成功与失败的方法 public interface NetCallBack { void Success(Object o); void Error(Throwable t); }
6.网络请求的工具类
package com.example.dell.versionupdatedemo05.utils; import android.os.Handler; import com.example.dell.versionupdatedemo05.NetCallBack; import com.google.gson.Gson; import java.io.IOException; import java.lang.reflect.Type; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class HttpUtils { //1.创建一个私有的静态的单列模式 private static volatile HttpUtils instance; //13.创建一个公有的Handler public Handler handler = new Handler() {}; private final OkHttpClient client; //2.创建一个私有的构造方法 private HttpUtils(){ //9.创建OkHttpClient