网络请求每天都在用。记一次简单网络请求过程。
第一步:创建retrofit
OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
//拦截器,可以不需要
.addInterceptor(new LogInterceptor(this))
.build();
retrofit = new Retrofit.Builder()
.client(mOkHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(mBaseUrl)
.build();
.addInterceptor 拦截器,可以进行网络请求的拦截与日志打印等操作
.baseUrl(mBaseUrl) 设置请求地址
第二步:创建service interface 接口
public interface MainApi {
@GET("api/v1/dictionary")
Call<DicInfoByKeyBean> getDicInfoByKey(@Query("name") String key);
}
这里可以有多种写法,我用的是Call回调
第三步:使用
// 创建 网络请求接口 的实例
MainApi apiService= BaseApp.retrofit.create(MainApi.class);
//对 发送请求 进行封装
Call<DicInfoByKeyBean> call = apiService.getDicInfoByKey("filterConfig");
call.enqueue(new Callback<DicInfoByKeyBean>() {
@Override
public void onResponse(Call<DicInfoByKeyBean> call, Response<DicInfoByKeyBean> response) {
//请求成功操作
if(response.body()!=null){
if(response.body().getCode()==200){
dicInfoByKeyBeanList = response.body().getData();
// Log.e(tag,"dicInfoByKeyBeanList="+new Gson().toJson(dicInfoByKeyBeanList));
}
}
}
@Override
public void onFailure(Call<DicInfoByKeyBean> call, Throwable t) {
//请求失败操作
}
});
注意一点:使用请求成功返回,response.body()获取不是数据值,应该使用response.body().getData() 获取