标签:
最近比较火的是OKhttp+picasso解析混合使用
接下来我们先上Okhttp抓抓数据。
显然Okhttp里面的那个onResponse 和 onFailure是非UI线程,那么我们改变他的话只有发送个通知出来让其他的UI线程来处理UI变化了,这个时候,屌丝王Handler出场了。
1.okhttp的get请求封装
直接上代码:
public static final int ok_error = -1;
public static final int ok_success = 1;
/**
* okhttp Post请求方式
*/
public static void OKdoGet(String url, final Handler handler) {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder().url(url).build();
// new call
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
handler.sendEmptyMessage(ok_error);
}
@Override
public void onResponse(final Response response) throws IOException {
String resultStr = response.body().string();
Message msg = new Message();
msg.what = ok_success;
msg.obj = resultStr;
handler.sendMessage(msg);
}
});
}
至于Handler里面怎么拿自行脑补。
2.Okhttp的post请求封装
/**
* Post请求的封装
*/
public static void OKdoPost(String url, final Handler handler,
FormEncodingBuilder builder) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).post(builder.build())
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request arg0, IOException arg1) {
handler.sendEmptyMessage(ok_error);
}
@Override
public void onResponse(Response arg0) throws IOException {
String resultStr = arg0.body().string();
Message msg = new Message();
msg.what = ok_success;
msg.obj = resultStr;
handler.sendMessage(msg);
}
});
}
/**
* Post请求的封装
*/
public static void OKdoPostWithCode(String url, final Handler handler,
FormEncodingBuilder builder, final int success, final int error) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).post(builder.build())
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request arg0, IOException arg1) {
handler.sendEmptyMessage(error);
}
@Override
public void onResponse(Response arg0) throws IOException {
String resultStr = arg0.body().string();
Message msg = new Message();
msg.what = success;
msg.obj = resultStr;
handler.sendMessage(msg);
}
});
}
因为他传值是不定的,所以咱把FormEncodingBuilder 给抽出来另外加,这样想怎么传就怎么传,再者不知道他是成功还是失败,所以就弄了多的两个判断的。
3.post请求的参数方法
/**
* post请求
*/
FormEncodingBuilder builder = new FormEncodingBuilder();
builder.add("sj_id", "1");
builder.add("xx", "1");
builder.add("page", page + "");
builder.add("oauth_token", "f5fbefc2bd9f538c3010fd24f57eb536");
OkHttpUtil.OKdoPost(ContextUrl.url, handler, builder);//Post请求方法调用
/**
* post请求 带请求码
*/
FormEncodingBuilder builder = new FormEncodingBuilder();
builder.add("sj_id", "1");
builder.add("xx", "1");
builder.add("page", page + "");
builder.add("oauth_token", "f5fbefc2bd9f538c3010fd24f57eb536");
OkHttpUtil.OKdoPostWithCode(ContextUrl.url, handler, builder, 3, 4);
OKhttp暂时说到这里,有啥加的再上。
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/jian_csdn/article/details/48135913