1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| 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() { @Override public void onSuccess(Response<String> response) { ioKgoResult.<String>getResult(response.body().toString()); } }); }
public void bitmapGet(){ OkGo.<Bitmap>get(Strings.URL_STR).execute(new BitmapCallback() { @Override public void onSuccess(Response<Bitmap> response) { //自行做处理 } }); }
/** * 封装返回任意类型的方法 * 说明:先执行convertResponse()将该方法的返回值返给onSuccess() */ public void test(){
OkGo.<Bean> get(Strings.URL_STR).execute(new AbsOkgoUtils<Bean>() { @Override public void onSuccess(Response<Bean> response) { //使用回调函数 Bean result = response.body(); ioKgoResult.<Bean>getResult(result); }
/** * 这个方法主要负责解析 * @param response * @return */ @Override public 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; } }); } }
|