简单记录使用OkGo进行网络请求
1.添加依赖
implementation 'com.lzy.net:okgo:3.0.4' implementation 'com.google.code.gson:gson:2.8.5'复制代码
2.新建java类
public class App extends Application { @Override public void onCreate() { super.onCreate(); initOkGo(); } private void initOkGo() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("result");//这里是添加日志拦截,可在logcat中输入result查看请求到的json数据 loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY); loggingInterceptor.setColorLevel(Level.INFO); builder.addInterceptor(loggingInterceptor); builder.readTimeout(10000, TimeUnit.MILLISECONDS); //全局的读取超时时间 builder.writeTimeout(10000, TimeUnit.MILLISECONDS); //全局的写入超时时间 builder.connectTimeout(20000, TimeUnit.MILLISECONDS); //全局的连接超时时间 // 其他统一的配置 OkGo.getInstance().init(this) //必须调用初始化 .setOkHttpClient(builder.build()) //建议设置OkHttpClient,不设置会使用默认的 .setRetryCount(0); }}复制代码
3.AndroidManifest.xml中添加android:name=".App",添加网络权限
4.MainActivity添加请求简单写法
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); OkGo.post("http://***.do") .params("account", "***") .params("password", "***") .execute(new JsonCallback () { @Override public void onSuccess(Response response) { if (response.body().getErrcode() == 0) {// 注意这里的toString,想显示全部内容需要重写toString方法 Toast.makeText(MainActivity.this, "成功了"+response.body().getData().toString(), } else { } } @Override public void onError(Response response) { super.onError(response); } }); }}复制代码
5.测试接口,复制返回的json数据再用gsonformat生成LoginBean类
6.自定义JsonCallback
public abstract class JsonCallbackextends AbsCallback { private Type type; private Class clz; public JsonCallback(Type type) { this.type = type; } public JsonCallback() { this.clz = clz; } @Override public T convertResponse(okhttp3.Response response) throws Throwable { ResponseBody body = response.body(); if (body == null) return null; T data = null; Gson gson = new Gson(); JsonReader jsonReader = new JsonReader(body.charStream()); if (type != null) { data = gson.fromJson(jsonReader, type); } else if (clz != null) { clz = gson.fromJson(jsonReader, clz); } else { Type genType = getClass().getGenericSuperclass(); Type type = ((ParameterizedType) genType).getActualTypeArguments()[0]; data = gson.fromJson(jsonReader, type); } return data; }}复制代码
注意(网络权限适配)
测试接口中的端口号不要写错,
AndroidManifest.xml记得添加网络权限,记得打开网络
9.0及以上手机记得加适配