OKHttpUtil

复制代码
import com.andata.xintong.pojo.resp.KeplerDownloadRespDTO;
import okhttp3.*;
import okhttp3.Request.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class OKHttpUtil {

    private static final Logger log = LoggerFactory.getLogger(OKHttpUtil.class);

    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");

    private static OkHttpClient httpClient = new OkHttpClient().newBuilder()
            .connectTimeout(1, TimeUnit.MINUTES)
            .readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES)
            .hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            })
            .build();

    public static Object json(String url, Object content,Map<String,String> headers) {
        log.info("json url:{} headers{}",url,headers);
        Builder builder = new Builder().url(url);
        if(headers != null && headers.size() > 0){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                builder.addHeader(entry.getKey(),entry.getValue());
            }
        }

        String reqParams= getReqString(content);
        log.info("okhttp json body {}", reqParams);
        RequestBody requestBody = RequestBody.create(JSON_TYPE, reqParams);
        builder.post(requestBody);
        return execute(builder);
    }

    public static Object get(String url,Map<String,String> headers) {
        log.info("get url:{} headers{}",url,headers);
        Builder builder = new Builder().url(url);
        if(headers != null && headers.size() > 0){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                builder.addHeader(entry.getKey(),entry.getValue());
            }
        }

        return execute(builder);
    }

    /**
     * 上传单个文件
     */
    public static Object upload(String url, Map<String, String> headers,  Map<String, Object> params) {
        log.info("upload url:{} headers{}",url,headers);
        Builder builder = new Builder().url(url);
        MultipartBody.Builder multiBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);


        if(headers != null && headers.size() > 0){
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String haderKey =  entry.getKey();
                log.info("upload haderKey:{},val:{}",haderKey,entry.getValue());
                multiBuilder.addFormDataPart(haderKey, entry.getValue());
            }
        }

        if(params != null && params.size() > 0){
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                Object value = entry.getValue();
                if(value instanceof byte[]){
                    byte[] bytes = (byte[]) value;
                    String key = entry.getKey();
                    log.info("--->upload file param filename:{},bytes.length:{}",key,bytes.length);
                    multiBuilder.addFormDataPart(
                            key,
                            key,
                            RequestBody.create(MultipartBody.FORM, bytes)
                           );
                }else {
                    String key = entry.getKey();
                    log.info("--->upload param key:{},val:{}",key,value);
                    multiBuilder.addFormDataPart(key, value.toString());
                }
            }
        }

        MultipartBody body = multiBuilder.build();
        builder.post(body);
        return execute(builder);
    }

    private static Object execute(Builder builder) {
        long startTime = System.currentTimeMillis();
        Request request = builder.build();
        Call call = httpClient.newCall(request);
        try (Response response = call.execute()) {
            Headers headers = response.headers();
            String disposition = headers.get("Content-disposition");
            Object result = null;
            if(disposition == null){
                result = response.body().string();

            }else {
                KeplerDownloadRespDTO downloadRespDTO = new KeplerDownloadRespDTO();
                downloadRespDTO.setBytes(response.body().bytes());
                downloadRespDTO.setContentDisposition(disposition);
                result = downloadRespDTO;
            }
            log.info("--cost:{} ms,body:{}",System.currentTimeMillis() - startTime,result);
            return result;
        } catch (IOException e) {
            log.error("okhttp happen error", e);
            throw new RuntimeException(e);
        }

    }

    private static String getReqString(Object content) {
        String reqParams=null;
        if(content instanceof String){
            reqParams = content.toString();
        }else{
            reqParams = JsonUtil.toJsonString(content);
        }
        return reqParams;
    }


}
复制代码

 

posted @   冬马党  阅读(243)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示