//首先我们先写一个接口
public interface IHttp { // GET请求 <T>void get(String url, Map<String,String>paramsMap,MyCallBack<T>callBack); // POST请求 <T>void post(String url,Map<String,String>paramsMap,MyCallBack<T>callBack); }//MyCallBack接口
public interface MyCallBack<T> { // 请求成功的方法 void success(T t); // 请求失败的方法 void faile(String msg); }//单例
/* * 将HttpUtils实例通过单例提供出去 * */ public class HttpUtils implements IHttp { // 创建私有的静态的本类对象 private static HttpUtils utils; // 创建私有的OkhttpClient对象 private OkHttpClient client; private HttpUtils() { client = new OkHttpClient(); } public static synchronized IHttp getInstance() { if (utils == null) { utils = new HttpUtils(); } return utils; } //http://www.baidu.com?name=zhangsan&pwd=123 @Override public <T> void get(String baseUrl, Map<String, String> paramsMap, final MyCallBack<T> callBack) { StringBuffer buffer = new StringBuffer(); buffer.append("?"); if (paramsMap != null && paramsMap.size() > 0) { for (String key : paramsMap.keySet()) { String value = paramsMap.get(key); buffer.append(key).append("=").append(value).append("&"); } buffer.toString().trim().substring(0, buffer.toString().trim().length() - 1); } String getUrl = buffer.toString().trim(); Request build = new Request.Builder().url(getUrl).build(); client.newCall(build).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callBack.faile(e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); callBack.success(getParseData(json, callBack)); } }); } /** * 通过反射的形式,将CallBack接口的实现类的类类型 * 然后将类类型传到Gson中,最后得到解析后的结果(类类型对应的实体) * * @param jsonData * @param callBack * @param <T> * @return */ private <T> T getParseData(String jsonData, MyCallBack<T> callBack) { Type[] interfacetypes = callBack.getClass().getGenericInterfaces(); Type[] types = ((ParameterizedType) interfacetypes[0]).getActualTypeArguments(); Type type = types[0]; Gson gson = new Gson(); T t = gson.fromJson(jsonData, type); return t; } //http://www.baidu.com @Override public <T> void post(String url, Map<String, String> paramsMap, final MyCallBack<T> callBack) { FormBody.Builder formBuilder = new FormBody.Builder(); for (String key : paramsMap.keySet()) { formBuilder.add(key, paramsMap.get(key)); } FormBody body = formBuilder.build(); Request build = new Request.Builder().url(url).post(body).build(); client.newCall(build).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { callBack.faile(e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { String json = response.body().string(); callBack.success(getParseData(json, callBack)); } }); } }