public class HttpUtils { private static final String TAG = "HttpUtils"; private static volatile HttpUtils instance; public static Handler handler = new Handler(); private HttpUtils() { } public static HttpUtils getInstance() { if (null == instance) { synchronized (HttpUtils.class) { if (instance == null) { instance = new HttpUtils(); } } } return instance; } /** * 对外提供的get请求 * * @param url * @param map * @param callback * @param cls */ public void get(String url, Map<String, String> map, final Callback callback, final Class cls) { // 对url和参数做一下拼接处理 // http://www.baidu.com/login?name=zs StringBuffer sb = new StringBuffer(); sb.append(url); // 如果存在? if (sb.indexOf("?") != -1) { // 如果?不在最后一位 if (sb.indexOf("?") != sb.length() - 1) { sb.append("&"); } } else { sb.append("?"); } for (Map.Entry<String, String> entry : map.entrySet()) { sb.append(entry.getKey()) .append("=") .append(entry.getValue()) .append("&"); } if (sb.indexOf("&") != -1) { sb.deleteCharAt(sb.lastIndexOf("&")); } Log.i(TAG, "get url: " + sb); OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder() .get() .url(sb.toString()) .build(); Call call = client.newCall(request); call.enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, final IOException e) { Log.e(TAG, "onFailure: " + e.getCause().getStackTrace() + e.getMessage()); handler.post(new Runnable() { @Override public void run() { callback.onFailed(e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String result = response.body().string(); Log.i(TAG, "onResponse: " + result); final Object o = GsonUtils.getInstance().fromJson(result, cls); handler.post(new Runnable() { @Override public void run() { callback.onSuccess(o); } }); } }); } /** * 封装的post请求 * * @param url * @param map * @param callback * @param cls */ public void post(String url, Map<String, String> map, final Callback callback, final Class cls) { OkHttpClient client = new OkHttpClient(); FormBody.Builder builder = new FormBody.Builder(); for (Map.Entry<String, String> entry : map.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } FormBody body = builder.build(); final Request request = new Request.Builder() .url(url) .post(body) .build(); Call call = client.newCall(request); call.enqueue(new okhttp3.Callback() { @Override public void onFailure(Call call, final IOException e) { Log.e(TAG, "onFailure: " + e.getCause().getStackTrace() + e.getMessage()); handler.post(new Runnable() { @Override public void run() { callback.onFailed(e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String result = response.body().string(); Log.i(TAG, "onResponse: " + result); final Object o = GsonUtils.getInstance().fromJson(result, cls); handler.post(new Runnable() { @Override public void run() { callback.onSuccess(o); } }); } }); } }
封装OKHttp的get和post请求模版
最新推荐文章于 2022-11-12 08:30:00 发布