OkGo的简单使用
一.返回值接口
public interface IOKgoResult<T> {public void getResult(T something);}
二.定义下载工具类
封装支持所有数据类型的下载
public class OKGoUtils {private static OKGoUtils OK_GO_UTILS = null;private IOKgoResult ioKgoResult;public static OKGoUtils getInstance(){if(OK_GO_UTILS == null)OK_GO_UTILS = new OKGoUtils();return OK_GO_UTILS;}private OKGoUtils(){}/*** 此方法必须调用* @param ioKgoResult*/public void setOKResult(IOKgoResult ioKgoResult){this.ioKgoResult = ioKgoResult;}/*** callback说明* StringCallback:操作字符串* BitmapCallback:操作图片*/public void stringGet(){OkGo.<String>get(Strings.URL_STR).execute(new StringCallback() {@Overridepublic void onSuccess(Response<String> response) {ioKgoResult.<String>getResult(response.body().toString());}});}public void bitmapGet(){OkGo.<Bitmap>get(Strings.URL_STR).execute(new BitmapCallback() {@Overridepublic void onSuccess(Response<Bitmap> response) {//自行做处理}});}/*** 封装返回任意类型的方法* 说明:先执行convertResponse()将该方法的返回值返给onSuccess()*/public void test(){OkGo.<Bean> get(Strings.URL_STR).execute(new AbsOkgoUtils<Bean>() {@Overridepublic void onSuccess(Response<Bean> response) {//使用回调函数Bean result = response.body();ioKgoResult.<Bean>getResult(result);}/*** 这个方法主要负责解析* @param response* @return*/@Overridepublic Bean convertResponse(okhttp3.Response response) {ResponseBody bean = response.body();try {String json_str = bean.string();Gson gson = new Gson();Bean bean1 = gson.fromJson(json_str,Bean.class);return bean1;} catch (IOException e) {e.printStackTrace();}return null;}});}}