Android网络请求利用第三方框架okHttp的工具类

public class HttpHelper {
    private final OkHttpClient mOkHttpClient;
    //用单例来写这个请求工具类  饿汉式 懒汉式
    private HttpHelper() {
        mOkHttpClient = new OkHttpClient();
    }
    //    static HttpHelper sHttpHelper = new HttpHelper();
    static HttpHelper sHttpHelper;
    public static HttpHelper getInstance() {
        if (sHttpHelper == null) {
            synchronized (HttpHelper.class) {
                if (sHttpHelper == null) {
                    sHttpHelper = new HttpHelper();
                }
            }
        }
        return sHttpHelper;
    }

    //提供一个方法来进行网络请求
    public void requestForAsyncGET(String url, final StringCallback stringCallback){
        //请求数据  OKHttp
        //1 OKHttpClient    在构造方法中去创建,不必创建多次了
        //2 Request
        Request request = new Request.Builder().url(url).build();
        //3 Call
        Call call = mOkHttpClient.newCall(request);
        //4 call.enqueue 异步
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Log.e(getClass().getSimpleName()+" xmg", "onFailure: "+e);
                //自己得接口的失败方法
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        stringCallback.onFail(e);
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(!response.isSuccessful()){
                    onFailure(call,new IOException("响应失败"));
                    return;
                }
                //xxxooo
                //自己得接口的成功方法
                final String string = response.body().string();
                /*Handler handler = new Handler();//handler当中的Looper是当前子线程中的looper*/
                Handler handler = new Handler(Looper.getMainLooper());//handler当中的Looper是主线程中的looper
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        stringCallback.onSuccess(string);
                    }
                });

            }
        });
    }
}


接口

public interface StringCallback {
    void onFail(IOException e);
    void onSuccess(String result);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值