美文网首页
okhttp简单封装

okhttp简单封装

作者: fufufufuli | 来源:发表于2019-02-27 13:31 被阅读0次

在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<String, ?> params) {
        return doRequest(getRequest(url, params, null));
    }

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

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

    public static HttpResult post(String url, Map<String, ?> params, Map<String, String> 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<String, String> headerMap) {
        return doRequest(postRequest(url, json, headerMap));
    }

    private static Request getRequest(String url, Map<String, ?> params, Map<String, String> 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<String, ?> params, String type, Map<String, String> 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<String, String> 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<String, String> headerMap) {
        RequestBody body = RequestBody.create(MEDIA_JSON, json);
        return buildRequest(url, body, headerMap);
    }

    private static RequestBody bodyFile(Map<String, ?> params) {
        for (Map.Entry<String, ?> 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<String, ?> params) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, ?> stringEntry : params.entrySet()) {
            builder.add(stringEntry.getKey(), stringEntry.getValue().toString());
        }
        return builder.build();
    }

    private static RequestBody bodyJson(Map<String, ?> 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通用简单封装

    CommonOkHttp--通用OkHttp简单封装 一个用于Java应用(非安卓)的OkHttp的简单封装git...

  • Android高级开发之【OkHttp】详解(附项目源码)

    文章大纲 一、OkHttp简介二、OkHttp简单使用三、OkHttp封装四、项目源码下载 一、OkHttp简介 ...

  • OkHttp简单封装

    使用链式编程思想封装网络请求客户端 } OkHttp初始化设置,请求返回处理 // ...

  • 简单封装OkHttp

    1.首先导入依赖 2.新建一个class 3.在Activity中调用

  • Okhttp简单封装

    一、Okhttp简介Android为我们提供了两种HTTP交互的方式: HttpURLConnection 和 A...

  • OKHttp简单封装

    接口: 管理类 使用

  • okhttp简单封装

    在github 维护最新代码https://github.com/fufufufuli/fuli-util 历史版本如下

  • OkHttp 的简单封装

    OkhttpIntegration 目前对应 OkHttp 版本3.8.1. Demo地址 使用 Android ...

  • OkHttp的简单封装

    关于OkHttp的基础使用可以看我之前写的这篇文章 但是每次写网络请求,都要写一大堆重复的东西,所以肯定要封装一下...

  • OkHttp的简单封装

    主要是记录一下封装的思路~ 封装的好处: 1.可复用性 2.与业务逻辑隔离 3.可扩展性 封装的思路: 封装一个公...

网友评论

      本文标题:okhttp简单封装

      本文链接:https://www.haomeiwen.com/subject/jjaxuqtx.html