public class HttpUtil {static HttpUtil util;private final OkHttpClient client;// 私有化构造方法private HttpUtil(){client = new OkHttpClient();}public static HttpUtil getInstance(){if(util == null){synchronized (HttpUtil.class){util = new HttpUtil();}}return util;}
public void httRequest(String url,final HttpRespon respon) {Request request = new Request.Builder().url(url).build();client.newCall(request).enqueue(new Callback() {// 请求失败 @Overridepublic void onFailure(Call call, IOException e) {e.printStackTrace();respon.onError("请求网络失败");}// 有响应 @Overridepublic void onResponse(Call call, Response response) throws IOException {if (!response.isSuccessful()) {respon.onError("请求网络失败");}// 获取响应bodyString json = response.body().string(); // 解析Json respon.parse(json); }});}}
定义的回调接口:
public abstract class HttpRespon<T> {//http返回的类型的泛型Class<T> t;public HttpRespon(Class<T> t){this.t = t;}// 请求失败时,回调的方法public abstract void onError(String msg); // 请求成功时,回调的方法public abstract void onSuccess(T t);public void parse(String json){if(TextUtils.isEmpty(json)){//请求失败onError("连接网络失败");return;}if(t == String.class){onSuccess((T) json);return;}T result = JsonUtil.parse(json, this.t);if(result == null){onError("Json解析失败");}else{onSuccess(result);}} }
调用的事例:
HttpUtil.getInstance().httRequest(Constant.SPLASH_URL, new HttpRespon<Ad>(Ad.class) {@Overridepublic void onError(String msg) {Log.i("fjl", msg);}@Overridepublic void onSuccess(Ad ad) {Intent intent = new Intent();intent.setClass(AdsActivity.this, AdDownloadService.class);intent.putExtra(AdDownloadService.AD_DATA, ad);startService(intent);}});