OkHttpClient简单封装

一.接口

public interface HttpListener {
    void onFinish(String reponse);
    void onError(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 onError(Exception e) {
                e.printStackTrace();
            }
        });

 

posted @ 2017-04-24 20:29  rorshach  阅读(755)  评论(0编辑  收藏  举报