很长时间只是知道okhttp这个网络请求框架很强大,也看了很多技术文章,但是只是懵懵懂懂,不知道该怎么使用。一个东西再强大,不会在项目中使用,一切都是零。
今天,搜索了好多资料,终于在项目中成功使用,很开心,在这里记录一下知识点,便于以后查看。下面记录一下,使用接口回掉进行网络请求的方法。
public DataProxy(Context context) {
this.context = context;
}
/**
* 获取缺勤回调接口
*/
public interface LeaveListListener {
void onGetLeaveListSucess(String data);
void onGetLeaveListFailed(boolean success);
}
public void getLeaveList( final LeaveListListener listener) {
String url = BaseApi.API_LEAVE_GETLEAVECOUNT1;//请求的url
RequestBody body = new FormBody.Builder()//添加参数
.add("userId", "1ac3")
.add("gradeCode", "1")
.add("gradeId","111111")
.add("month", "3")
.build();
Request request = new Request.Builder().url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onGetLeaveListFailed(false);//失败回调方法
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String data = response.body().string();//成功请求数据
listener.onGetLeaveListSucess(data);//成功回调方法
}
});
}
下面实在activity中调用请求的方法
dataProxy = new DataProxy(context);//自定义工具类
dataProxy.getLeaveList(this);
需要导入两个依赖包
okhttp-3.4.1.jar
okio-1.4.0.jar