1. 程式人生 > >Okhttp工具類

Okhttp工具類

public class OkHttpUtiles {
private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HTTP_SUCCESS:
                    String data = (String) msg.obj;
                    //
                    httpListener.success(data);
                    break;
                case HTTP_ERROR:
                    break;
            }
        }
    };
    private final int HTTP_ERROR = 100;
    private final int HTTP_SUCCESS = 313;
    private HttpListener httpListener;

    //GET請求
    public OkHttpUtiles get(String url) {
        //例項化OkHttpClient
        OkHttpClient client = new OkHttpClient();
        //Request.Builder()物件
        Request resquest = new Request.Builder()
                .get()
                .url(url)
                .build();
        //非同步請求enqueue
        client.newCall(resquest).enqueue(new Callback() {
            //失敗
            @Override
            public void onFailure(Call call, IOException e) {
                //傳送失敗 訊息
                handler.sendEmptyMessage(HTTP_ERROR);
            }

            //成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Message obtain = Message.obtain();
                obtain.what = HTTP_SUCCESS;
                obtain.obj = string;
                handler.sendMessage(obtain);
            }
        });
        return this;
    }
    //傳遞介面
    public void result(HttpListener httpListener) {
        this.httpListener = httpListener;
    }

//介面回撥     這裡寫到iml包裡了
    public interface HttpListener{
        void success(String data);
        void errror();
}


}