OkHttp加日志拦截器

package mmy.bawei.com.yklx1.net;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpUtils {

private int HTTP_SUCCESS = 1000;
private int HTTP_FALL = 1000;

private HttpListener mHttpListener;
private OkHttpClient client;

public OkHttpUtils get(String url){
    doHttp(url,0,null);
    return this;
}

public OkHttpUtils post(String url, FormBody.Builder bodyBuilder){
    doHttp(url,1,bodyBuilder);
    return this;
}

private void doHttp(String url, int i, FormBody.Builder bodyBuilder) {
    client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Log.i("intercept", request.url().host());

            return chain.proceed(request);
        }
    }).build();
    Request.Builder builder = new Request.Builder();

    if (i == 0){
        builder.get();
    }else {
        builder.post(bodyBuilder.build());
    }
    builder.url(url);
    Request request = builder.build();

    final Message message = Message.obtain();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            message.obj = e.getMessage();
            message.what = HTTP_FALL;
            handler.sendMessage(message);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            message.obj = response.body().string();
            message.what = HTTP_SUCCESS;
            handler.sendMessage(message);
        }
    });
}

public Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == HTTP_SUCCESS){
            String data = (String) msg.obj;
            mHttpListener.success(data);
        }else {
            String error = (String) msg.obj;
            mHttpListener.fail(error);
        }
    }
};

public void result(HttpListener mHttpListener) {
    this.mHttpListener = mHttpListener;
}

public interface HttpListener{
    void success(String data);

    void fail(String error);
}

}

你可能感兴趣的:(OkHttp加日志拦截器)