安卓学习零零碎碎也有一段时间了,根据iOS的经验封装一下OkHttp,方便自己的使用习惯。
1、新建一个文件LFCallBack,定义两个函数,一个成功,一个失败。
public interface LFCallBack {
public void successCallBack(String json);
public void failueCallBack(String error);
}
2、新建一个LFNetWorking,实现post方法。
public class LFNetWorking {
public void post(RequestBody paras, String url, final LFCallBack lfCallBack) {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.post(paras)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
// TODO Auto-generated method stub
final String json = response.body().string();
lfCallBack.successCallBack(json);
}
@Override
public void onFailure(Call call, IOException e) {
// TODO Auto-generated method stub
lfCallBack.failueCallBack(e.getMessage());
}
});
}
}
3、使用
LFNetWorking lf = new LFNetWorking();
RequestBody paras = new FormBody.Builder()
.add("UserName", ac)
.add("Password", pwd)
.add("DeviceId", "123")
.build();
lf.post(paras, API.User_Login, new LFCallBack() {
@Override
public void successCallBack(String json) {
Log.i("007success:", json);
}
@Override
public void failueCallBack(String error) {
Log.i("007error:", error);
}
});
//传参数有待优化
网友评论