okhttp简单封装

在github 维护最新代码
https://github.com/fufufufuli/fuli-util

历史版本如下

package cn.util;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
    private static volatile HttpUtil instance;
    private static OkHttpClient client;
    private static final int CONNECT_TIMEOUT = 10;
    private static final int READ_TIMEOUT = 20;
    private static final int MAX_IDLE_CONNECTIONS = 5;
    private static final int KEEP_ALIVE_DURATION = 5;
    public static final String TYPE_JSON = "json";
    public static final String TYPE_FORM = "from";
    public static final String TYPE_FILE = "file";
    public static final MediaType MEDIA_JSON = MediaType.parse("application/json; charset=utf-8");

    private HttpUtil(OkHttpClient client) {
        if (client == null) {
            ConnectionPool pool = new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.MINUTES);
            HttpUtil.client = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .connectionPool(pool)
                .build();
        } else {
            HttpUtil.client = client;
        }
    }

    private static HttpUtil init() {
        if (instance == null) {
            synchronized (HttpUtil.class) {
                if (instance == null) {
                    instance = new HttpUtil(null);
                }
            }
        }
        return instance;
    }

    public static HttpUtil getInstance() {
        return init();
    }

    OkHttpClient getOkHttpClient() {
        return HttpUtil.client;
    }

    public static HttpResult get(String url, Map params) {
        return doRequest(getRequest(url, params, null));
    }

    public static HttpResult get(String url, Map params, Map headerMap) {
        return doRequest(getRequest(url, params, headerMap));
    }

    public static HttpResult post(String url, Map params, String type) {
        return doRequest(postRequest(url, params, type, null));
    }

    public static HttpResult post(String url, Map params, Map headerMap, String type) {
        return doRequest(postRequest(url, params, type, headerMap));
    }

    /**
     * jsonString
     */
    public static HttpResult post(String url, String json) {
        return doRequest(postRequest(url, json, null));
    }

    /**
     * jsonString
     */
    public static HttpResult post(String url, String json, Map headerMap) {
        return doRequest(postRequest(url, json, headerMap));
    }

    private static Request getRequest(String url, Map params, Map headerMap) {
        log.debug("请求参数为{}", params);
        StringBuilder sb = new StringBuilder(url);
        if (params != null && params.size() > 0) {
            sb.append("?");
            for (Map.Entry kv : params.entrySet()) {
                sb.append(kv.getKey());
                sb.append("=");
                sb.append(kv.getValue());
                sb.append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        log.debug("请求URL为{}", sb.toString());
        if (headerMap != null && headerMap.size() > 0) {
            return new Request.Builder().url(sb.toString()).get().headers(Headers.of(headerMap)).build();
        }
        return new Request.Builder().url(sb.toString()).get().build();
    }

    private static Request postRequest(String url, Map params, String type, Map headerMap) {
        RequestBody body;
        switch (type) {
            case TYPE_JSON:
                body = bodyJson(params);
                break;
            case TYPE_FORM:
                body = bodyForm(params);
                break;
            case TYPE_FILE:
                body = bodyFile(params);
                break;
            default:
                log.error("没有对应的post提交类型{}", type);
                return null;
        }
        return buildRequest(url, body, headerMap);
    }

    private static Request buildRequest(String url, RequestBody body, Map headerMap) {
        if (body != null && headerMap != null) {
            return new Request.Builder().url(url).headers(Headers.of(headerMap)).post(body).build();
        } else {
            if (body != null) {
                return new Request.Builder().url(url).post(body).build();
            }
            if (headerMap != null) {
                return new Request.Builder().url(url).headers(Headers.of(headerMap)).build();
            }
        }
        return new Request.Builder().url(url).build();
    }

    private static Request postRequest(String url, String json, Map headerMap) {
        RequestBody body = RequestBody.create(MEDIA_JSON, json);
        return buildRequest(url, body, headerMap);
    }

    private static RequestBody bodyFile(Map params) {
        for (Map.Entry stringEntry : params.entrySet()) {
            if (stringEntry.getValue() instanceof File) {
                File file = (File) stringEntry.getValue();
                return new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file))
                    .build();
            }
        }
        return null;
    }

    private static RequestBody bodyForm(Map params) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry stringEntry : params.entrySet()) {
            builder.add(stringEntry.getKey(), stringEntry.getValue().toString());
        }
        return builder.build();
    }

    private static RequestBody bodyJson(Map params) {
        String json = JSON.toJSONString(params);
        log.debug("请求参数为{}", json);
        return RequestBody.create(MEDIA_JSON, json);
    }

    private static HttpResult doRequest(final Request request) {
        try {
            init();
            Response response = client.newCall(request).execute();
            return responseResult(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static HttpResult responseResult(Response response) {
        String result = null;
        if (response.isSuccessful() && response.body() != null) {
            try (Reader reader = response.body().charStream()) {
                int capacity = (int) response.body().contentLength();
                if (capacity < 0) {
                    capacity = 4096;
                }
                //CharArrayBuffer buffer = new CharArrayBuffer(capacity);
                StringBuilder buffer = new StringBuilder(capacity);
                char[] tmp = new char[1024];
                int l;
                while ((l = reader.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                result = buffer.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            result = response.message();
        }
        return new HttpResult(response.code(), result);
    }


}

你可能感兴趣的:(okhttp简单封装)