首页 > 代码库 > OkHttpClient简单封装

OkHttpClient简单封装

一.接口

public interface HttpListener {
    void onFinish(String reponse);
    void one rror(Exception e);
}

 

二.OkHttpUtil

public class OkHttpUtil {

    public static void AsyncGet(String url, final HttpListener listener){
        OkHttpClient http = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .build();

        Call call = http.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.onFinish(response.body().string());
            }
        });
    }
}

 

三.调用

OkHttpUtil.AsyncGet("http://www.baidu.com", new HttpListener() {
            @Override
            public void onFinish(String reponse) {
                Log.e("log", reponse);
            }

            @Override
            public void one rror(Exception e) {
                e.printStackTrace();
            }
        });

 

OkHttpClient简单封装