最近有时间看了OkHttp网络请求,体验感觉上升了好几个档次,get、post、文件的上传和下载的支持都比较好,很多人都选择了OkHttp。那么问题来了,OkHttp通过enqueue方法确实是开启了一个线程进行了请求,但是回调的onFailure和onResponse方法仍然还是在那个线程里,okhttp有没有提供一个方法,能够进行异步请求并且最后回调时又回到主线程?显然是没有提供了,但是我们可以通过简单的handler来处理一下,下面来封装一下我们的http请求
1、post请求,map为参数
/**
* post请求 map为body
*
* @param url
* @param map
* @param callback
*/
public void post(String url, Map map,final HttpCallback callback) {
// FormBody.Builder builder = new FormBody.Builder();
// FormBody body=new FormBody.Builder().add("key", "value").build();
/**
* 创建请求的参数body
*/
FormBody.Builder builder = new FormBody.Builder();
/**
* 遍历key
*/
if (null != map) {
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = "
+ entry.getValue());
builder.add(entry.getKey(), entry.getValue().toString());
}
}
RequestBody body = builder.build();
Request request = new Request.Builder().url(url).post(body).build();
onStart(callback);
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(final Response response) throws IOException {
// TODO Auto-generated method stub
if (response.isSuccessful()) {
onSuccess(callback, response.body().string());
} else {
onError(callback, response.message());
}
}
@Override
public void onFailure(Request arg0, IOException arg1) {
// TODO Auto-generated method stub
arg1.printStackTrace();
onError(callback, arg1.getMessage());
}
});
}
这里我们创建了FormBody为请求的参数、Request的post请求、enqueue为异步的请求,如果用的execute为同步的请求
2、post请求,json为参数
/**
* post请求,json数据为body
*
* @param url
* @param json
* @param callback
*/
public void postJson(String url, String json, final HttpCallback callback) {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).build();
onStart(callback);
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
// TODO Auto-generated method stub
if (response.isSuccessful()) {
onSuccess(callback, response.body().string());
} else {
onError(callback, response.message());
}
}
@Override
public void onFailure(Request arg0, IOException arg1) {
// TODO Auto-generated method stub
onError(callback, arg1.getMessage());
arg1.printStackTrace();
}
});
}
JSON为MediaType.parse(“application/json; charset=utf-8”)
3、get请求
/**
* get请求
* @param url
* @param callback
*/
public void get(String url, final HttpCallback callback) {
Request request = new Request.Builder().url(url).build();
onStart(callback);
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
// TODO Auto-generated method stub
if (response.isSuccessful()) {
onSuccess(callback, response.body().string());
} else {
onError(callback, response.message());
}
}
@Override
public void onFailure(Request arg0, IOException arg1) {
// TODO Auto-generated method stub
onError(callback, arg1.getMessage());
arg1.printStackTrace();
}
});
}
get请求相对于post来说简单点,上面说的在请求回来时有没有能够进行异步请求并且最后回调时又回到主线程?用handler我们这样处理
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
// 需要在主线程的操作。
}
});
在使用的使用我们就可以直接调用了
new HttpUtils().post(url,null,new HttpCallback() {
@Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(MainActivity.this, "start", Toast.LENGTH_LONG).show();
}
@Override
public void onSuccess(String data) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "test", Toast.LENGTH_LONG).show();
System.out.println("data:"+data);
tv.setText(data);
}
@Override
public void onError(String msg) {
// TODO Auto-generated method stub
super.onError(msg);
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG).show();
}
});
最后记得加上网络请求的权限
下面来看看我们封装的HttpUtil 类
package com.example.okhttpdemo;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
/**
* okhttp请求
* @author Flyjun
*
*/
public class HttpUtils {
public static String TAG="debug-okhttp";
public static boolean isDebug=true;
private OkHttpClient client;
// 超时时间
public static final int TIMEOUT = 1000 * 60;
//json请求
public static final MediaType JSON = MediaType
.parse("application/json; charset=utf-8");
private Handler handler = new Handler(Looper.getMainLooper());
public HttpUtils() {
// TODO Auto-generated constructor stub
this.init();
}
private void init() {
client = new OkHttpClient();
// 设置超时时间
client.newBuilder().connectTimeout(TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(TIMEOUT, TimeUnit.SECONDS)
.readTimeout(TIMEOUT, TimeUnit.SECONDS).build();
}
/**
* post请求,json数据为body
*
* @param url
* @param json
* @param callback
*/
public void postJson(String url, String json, final HttpCallback callback) {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).build();
onStart(callback);
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
// TODO Auto-generated method stub
if (response.isSuccessful()) {
onSuccess(callback, response.body().string());
} else {
onError(callback, response.message());
}
}
@Override
public void onFailure(Request arg0, IOException arg1) {
// TODO Auto-generated method stub
onError(callback, arg1.getMessage());
arg1.printStackTrace();
}
});
}
/**
* post请求 map为body
*
* @param url
* @param map
* @param callback
*/
public void post(String url, Map map,final HttpCallback callback) {
// FormBody.Builder builder = new FormBody.Builder();
// FormBody body=new FormBody.Builder().add("key", "value").build();
/**
* 创建请求的参数body
*/
FormBody.Builder builder = new FormBody.Builder();
/**
* 遍历key
*/
if (null != map) {
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = "
+ entry.getValue());
builder.add(entry.getKey(), entry.getValue().toString());
}
}
RequestBody body = builder.build();
Request request = new Request.Builder().url(url).post(body).build();
onStart(callback);
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(final Response response) throws IOException {
// TODO Auto-generated method stub
if (response.isSuccessful()) {
onSuccess(callback, response.body().string());
} else {
onError(callback, response.message());
}
}
@Override
public void onFailure(Request arg0, IOException arg1) {
// TODO Auto-generated method stub
arg1.printStackTrace();
onError(callback, arg1.getMessage());
}
});
}
/**
* get请求
* @param url
* @param callback
*/
public void get(String url, final HttpCallback callback) {
Request request = new Request.Builder().url(url).build();
onStart(callback);
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Response response) throws IOException {
// TODO Auto-generated method stub
if (response.isSuccessful()) {
onSuccess(callback, response.body().string());
} else {
onError(callback, response.message());
}
}
@Override
public void onFailure(Request arg0, IOException arg1) {
// TODO Auto-generated method stub
onError(callback, arg1.getMessage());
arg1.printStackTrace();
}
});
}
/**
* log信息打印
* @param params
*/
public void debug(String params){
if(false == isDebug){
return;
}
if(null == params){
Log.d(TAG, "params is null");
}else{
Log.d(TAG, params);
}
}
private void onStart(HttpCallback callback) {
if (null != callback) {
callback.onStart();
}
}
private void onSuccess(final HttpCallback callback, final String data) {
debug(data);
if (null != callback) {
handler.post(new Runnable() {
public void run() {
// 需要在主线程的操作。
callback.onSuccess(data);
}
});
}
}
private void onError(final HttpCallback callback,final String msg) {
if (null != callback) {
handler.post(new Runnable() {
public void run() {
// 需要在主线程的操作。
callback.onError(msg);
}
});
}
}
/**
* http请求回调
*
* @author Flyjun
*
*/
public static abstract class HttpCallback {
// 开始
public void onStart() {};
// 成功回调
public abstract void onSuccess(String data);
// 失败回调
public void onError(String msg) {};
}
}
关于更多的使用可以看看okhttp的官网
okhttp3