Android OkHttp3工具类封装



public class OkHttpUtil {
    //静态本类对象
    private static OkHttpUtil okHttpUtil;
    private OkHttpClient okHttpClient;

    //私有化构造方法
    private OkHttpUtil() {
        okHttpClient = new OkHttpClient.Builder().build();
    }

    //公共的供外部访问的方法
    public static OkHttpUtil getInstance() {
        if (okHttpUtil == null) {
            synchronized (OkHttpUtil.class) {
                if (okHttpUtil == null) {
                    okHttpUtil = new OkHttpUtil();
                }
            }
        }
        return okHttpUtil;
    }

    public void get(String url, Map map, final NetworkCallback networkCallback) {

        if (map != null && map.size() > 0) {

            StringBuffer sb = new StringBuffer(url);
            sb.append("?");
            Set set = map.keySet();
            for (String str : set) {

                sb.append(str).append("=").append(map.get(str)).append("&");
            }
            url = sb.substring(0, sb.length() - 1);
        }

        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                networkCallback.error(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                networkCallback.successful(string);
            }
        });
    }

    public void post(String url, JSONObject json, final NetworkCallback networkCallback) {


//              RequestBody body = new FormBody.Builder().build();

        MediaType JSON = MediaType.parse("text/x-markdown; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json.toString());


        Request request = new Request.Builder().url(url).method("POST", body).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                networkCallback.error(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                networkCallback.successful(string);
            }
        });
    }
}

你可能感兴趣的:(Android,移动,网络请求)