首页 > 其他分享 >OKhttpClient 简单使用总结

OKhttpClient 简单使用总结

时间:2024-11-22 09:47:53浏览次数:1  
标签:总结 builder String url Builder Request OKhttpClient 简单 response

<!-- okhttp -->

<dependency>

   <groupId>com.squareup.okhttp3</groupId>

  <artifactId>okhttp</artifactId>

   <version>3.6.0</version>

</dependency>

<!-- okhttp /-->

 

@Service
public class OKHttpClient implements InitializingBean{
    private static int DEFAULT_READ_TIMEOUT_MILLIS = 500;
    private static int DEFAULT_CONNECT_TIMEOUT_MILLIS = 500;
    private static int DEFAULT_WRITE_TIMEOUT_MILLIS = 500;

    private OkHttpClient client;

    /**
     * 处理post请求,兼容原httpClient请求
     * @param baseUrl
     * @param url
     * @param nvp
     * @param headers
     * @return
     * @throws Exception
     */
    public String post(String baseUrl, String url, List<NameValuePair> nvp, Header... headers)
            throws Exception {
        //Request build对象
        Request.Builder builder = getBuilder(baseUrl, url);
        //处理headers
        doHeaders(builder, headers);
        //处理请求参数
        doPostRequestBody(builder, nvp);
        //创建Request
        Request request = builder.build();
        //同步请求并获取Response
        Response response = client.newCall(request).execute();
        //校验并返回
        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("OKHttpClientApi post response: " + response);
        }
    }

    /**
     * 处理get请求,兼容原httpClient请求
     * @param baseUrl
     * @param url
     * @param nvp
     * @param headers
     * @param cookies
     * @return
     * @throws Exception
     */
    public String get(String baseUrl, String url, List<NameValuePair> nvp, List<Header> headers, List<Cookie> cookies)
            throws Exception {
        //Request build对象,get请求没有method方法,默认是PUT方式请求,直接在URL做参数处理
        Request.Builder builder = getBuilder(baseUrl, url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(nvp, "UTF-8")));
        builder.get();
        //处理headers
        doHeaders(headers, builder);
        //创建Request
        Request request = builder.build();
        //处理cookies
        doCookies(cookies, request, client);
        //同步请求并获取Response
        Response response = client.newCall(request).execute();
        //校验并返回
         if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("OKHttpClientApi get response: " + response);
        }
    }

    /**
     * post请求参数写入Request.Builder
     * @param builder
     * @param nvp
     */
    private void doPostRequestBody(Request.Builder builder, List<NameValuePair> nvp) {
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        if (!CollectionUtils.isEmpty(nvp)) {
            for (NameValuePair bean : nvp) {
                bodyBuilder.add(bean.getName(), bean.getValue());
            }
            builder.post(bodyBuilder.build());
        }else {
            builder.post(null);
        }
    }

    /**
     * 获取Request.Builder
     * @param baseUrl
     * @param url
     * @return
     */
    private Request.Builder getBuilder(String baseUrl, String url) {
        return new Request.Builder().url(String.format("%s%s", baseUrl, url));
    }

    /**
     * 处理请求cookies
     * @param cookies
     * @param request
     * @param client
     */
    private void doCookies(List<Cookie> cookies, Request request, OkHttpClient client) {
        if (!CollectionUtils.isEmpty(cookies)) {
            client.cookieJar().saveFromResponse(request.url(), convertCookies(cookies));
        }
    }

    /**
     * 处理请求headers
     * @param headers
     * @param builder
     */
    private void doHeaders(List<Header> headers, Request.Builder builder) {
        if (!CollectionUtils.isEmpty(headers)) {
            Headers.Builder headeBuilder = new Headers.Builder();
            for (Header header : headers) {
                headeBuilder.add(header.getName(), header.getValue());
            }
            builder.headers(headeBuilder.build());
        }
    }

    /**
     * 处理请求headers
     * @param headers
     * @param builder
     */
    private void doHeaders(Request.Builder builder, Header[] headers) {
        if (headers != null && headers.length > 0) {
            Headers.Builder headeBuilder = new Headers.Builder();
            for (Header header : headers) {
                headeBuilder.add(header.getName(), header.getValue());
            }
            builder.headers(headeBuilder.build());
        }
    }

    /**
     * cookie转化
     * @param cookies
     * @return
     */
    private List<okhttp3.Cookie> convertCookies(List<Cookie> cookies) {
        List<okhttp3.Cookie> list = new ArrayList<>();
        okhttp3.Cookie.Builder builder;
        for (Cookie cookie : cookies) {
            builder = new okhttp3.Cookie.Builder();
            builder.name(cookie.getName())
                   .domain(cookie.getDomain())
                   .expiresAt(cookie.getExpiryDate().getTime())
                   .path(cookie.getPath())
                   .value(cookie.getValue());
            if (cookie.isSecure()) {
                builder.secure();
            }
            list.add(builder.build());
        }
        return list;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        client = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .readTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .writeTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)
                .build();
    }
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 基于okhttp 的 httpclient 框架
 *
 * @author lixing
 */
@Component
public class OkHttpProxy implements InitializingBean {

    private final static Logger LOGGER = LoggerFactory.getLogger(OkHttpProxy.class);

    @Autowired
    OkHttpConfig okHttpConfig;

    private static OkHttpClient okHttpClient;

    private int maxIdleConnections;
    private long keepAliveDuration;
    private long connectTimeout;
    private long readTimeout;

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

    @PostConstruct
    public void init() {
        connectTimeout = okHttpConfig.getOkhttpConnectTimeout() == null ? 0 : Integer.parseInt(okHttpConfig.getOkhttpConnectTimeout());
        readTimeout = okHttpConfig.getOkhttpReadTimeout() == null ? 0 : Integer.parseInt(okHttpConfig.getOkhttpReadTimeout());
        maxIdleConnections = okHttpConfig.getOkhttpMaxIdleConnections() == null ? 0 : Integer.parseInt(okHttpConfig.getOkhttpMaxIdleConnections());
        keepAliveDuration = okHttpConfig.getOkhttpKeepAliveDuration() == null ? 0 : Integer.parseInt(okHttpConfig.getOkhttpKeepAliveDuration());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (0 != connectTimeout) {
            builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
        }
        if (0 != readTimeout) {
            builder.readTimeout(readTimeout, TimeUnit.SECONDS);
        }
        if (0 != maxIdleConnections && 0 != keepAliveDuration) {
            ConnectionPool pool = new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
            builder.connectionPool(pool);
        }
        okHttpClient = builder.build();
    }


    public String doGet(String url, String queryString, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder reqBuilder = new Request.Builder();
        this.prepareHeader(headerMap, reqBuilder);
        Request getRequest = reqBuilder.url(url + "?" + queryString).get().build();
        response = okHttpClient.newCall(getRequest).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }

    public String doPost(String url, String queryString, Map<String, String> paramMap, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder reqBuilder = new Request.Builder();
        if (headerMap != null) {
            for (String key : headerMap.keySet()) {
                reqBuilder.addHeader(key, headerMap.get(key));
            }
        }
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        if (paramMap != null) {
            for (String key : paramMap.keySet()) {
                formBodyBuilder.add(key, paramMap.get(key));
            }
        }
        RequestBody body = formBodyBuilder.build();
        if (queryString != null) {
            url = url + "?" + queryString;
        }
        Request postRequest = reqBuilder.url(url).post(body).build();
        response = okHttpClient.newCall(postRequest).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }

    public String doMix(String url, String queryString, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder reqBuilder = new Request.Builder();
        this.prepareHeader(headerMap, reqBuilder);
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        RequestBody body = formBodyBuilder.build();
        Request postRequest = reqBuilder.url(url + "?" + queryString).post(body).build();
        response = okHttpClient.newCall(postRequest).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }

    public String doMix(String url, String queryString, Map<String, String> bodyParamMap, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder reqBuilder = new Request.Builder();
        this.prepareHeader(headerMap, reqBuilder);
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        if (bodyParamMap != null) {
            for (String key : bodyParamMap.keySet()) {
                formBodyBuilder.add(key, headerMap.get(key));
            }
        }
        RequestBody body = formBodyBuilder.build();
        Request postRequest = reqBuilder.url(url + "?" + queryString).post(body).build();
        response = okHttpClient.newCall(postRequest).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }

    public String doPostByJson(String url, String json, Map<String, String> headerMap) throws Exception {
        Response response ;
        Request.Builder builder = new Request.Builder().url(url);
        this.prepareHeader(headerMap, builder);
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = builder.post(requestBody).build();
        response = okHttpClient.newCall(request).execute();
        this.errorResponseLog(response, url);
        return response.body().string();
    }


    private void prepareHeader(Map<String, String> headerMap, Request.Builder builder) {
        if (headerMap != null) {
            for (String key : headerMap.keySet()) {
                builder.addHeader(key, headerMap.get(key));
            }
        }
    }

    private void errorResponseLog(Response response, String url) throws Exception {
        if (response == null) {
            LOGGER.error("okhttpclient call fail,url={},  message=response is null", url);
            throw new Exception(String.format("http call fail,url=%s,  status=null", url));
        }
        if (!response.isSuccessful()) {
            LOGGER.error("okhttpclient call fail,url={},  message={}", url, response.body().string());
            throw new Exception(String.format("http call fail,url=%s,  status=%s", url, response.code()));
        }
    }
}

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * okHttp config
 *
 * @author huangbingchi on 2018/1/25 下午1:46
 * @version 1.0.0
 */
@Configuration
public class OkHttpConfig implements java.io.Serializable {

    @Value("${okhttp.connectTimeout}")
    private String okhttpConnectTimeout;

    @Value("${okhttp.readTimeout}")
    private String okhttpReadTimeout;

    @Value("${okhttp.keepAliveDuration}")
    private String okhttpKeepAliveDuration;

    @Value("${okhttp.maxIdleConnections}")
    private String okhttpMaxIdleConnections;

    @Value("${okhttp.hystrix.threshold}")
    private String hystrixThreshold;

    @Value("${okhttp.hystrix.sleep}")
    private String hystrixSleep;

    @Value("${okhttp.hystrix.threshold.percentage}")
    private String hystrixThresholdPercentage;

    @Value("${okhttp.hystrix.threads}")
    private String hystrixThreads;

    @Value("${okhttp.hystrix.fallback.accepts}")
    private String hystrixFallbackAccepts;

#okhttp配置
okhttp.connectTimeout=1
okhttp.readTimeout=1
okhttp.keepAliveDuration=0
okhttp.maxIdleConnections=0
#okhttp熔断配置
okhttp.hystrix.threshold=20
okhttp.hystrix.sleep=20000
okhttp.hystrix.threshold.percentage=50
okhttp.hystrix.threads=30
okhttp.hystrix.fallback.accepts=500

 

标签:总结,builder,String,url,Builder,Request,OKhttpClient,简单,response
From: https://www.cnblogs.com/ryanace1988/p/18562086

相关文章

  • java题目集4-6总结
    一、前言概括:经过了三次java的大作业的练习,也算是深入java了。这三次大作业的难度是层层递进的,虽然一次比一次难,但是每一次大作业都是基于前面大作业的知识点。所以每一次大作业认真完成,并认真总结知识点,多花点时间,大作业还是勉强可以完成。1.知识点:大作业4:大作业四还是答题......
  • 多线程编程入门Thread_Task_async_await简单秒懂
    `usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespace多线程编......
  • 2024-2025-1 20241305 《计算机基础与程序设计》第九周学习总结
    作业信息这个作业属于哪个课程[2024-2025-1-计算机基础与程序设计(https://edu.cnblogs.com/campus/besti/2024-2025-1-CFAP))这个作业要求在哪里2024-2025-1计算机基础与程序设计第九周作业这个作业的目标1、操作系统责任2、内存与进程管理3、分时系统4、CPU调......
  • Next.js项目App目录如何简单集成markdown博客
    文章原文:Next.js项目App目录如何简单集成markdown博客此教程适用于比较简单的项目实现,如果你是刚入门next,并且不想用太复杂的方式去实现一个博客项目,那么这个教程就挺适合你的。Next.js官方关于markdown的文档有说明过如何渲染markdown,也是针对App目录的,但我尝试过并不太行,可能......
  • QOJ6958-复杂的双树上问题以及简单的解决方式
    题面原题链接思路我们考虑如何判断一对\(T_1,T_2\)是否合法。首先,我们可以发现\(T_2\)上的边权只能有至多一组合法解,这是因为对于任意一条边连接\(u,v\),它的边权必然是\(dis_1(u,v)\),所以事实上我们是没有权限给\(T_2\)任意赋权的,这样题目就简单了一些。那么,我们如何......
  • 21~23集训测试题总结
    23集训测试题(10.8)密码锁这题数据量较小,可以直接暴力枚举所有密码情况并一一判断暴力代码#include<iostream>#include<cstring>#include<algorithm>usingnamespacestd;structL{intstate[6];booloperator<(constL&b)const{for(inti......
  • KOA 入门,简单实现用户注册和登录逻辑
    koa首先来介绍一下什么是koa。koa是由Express背后的团队设计的一个新的Web框架,旨在成为Web应用和API的更小、更具表现力和更强大的基础。通过利用异步函数,koa允许你放弃回调并大大提高错误处理能力。koa的核心中没有捆绑任何中间件,它提供了一套优雅的方法,使编写......
  • 【基于PyTorch的简单多层感知机(MLP)神经网络(深度学习经典代码实现)】
    importtorchfromtorchvisionimporttransformsfromtorchvisionimportdatasetsfromtorch.utils.dataimportDataLoaderimporttorch.nn.functionalasFimporttorch.optimasoptim#准备数据集batch_size=64transform=transforms.Compose([transforms.......
  • 简单几步,基于云主机快速为Web项目添加AI助手
    在华为开发者空间,借助华为云对话机器人服务CBS您可以零代码创建一个大模型RAG(Retrieval-AugmentedGeneration,即检索增强生成)应用,来实现AI助手的智能问答能力。本实验借助华为云CBS提供的可访问API,在项目代码中通过几行代码引入AI助手,用户就可以在网站上看到一个AI助手......
  • 最简单的纯CSS3滑动开关按钮特效
    在线预览  下载HTML结构该滑动按钮的基本HTML结构使用一个<label>元素来包裹一个<input>元素和2个<span>元素。span.text-switch是按钮上的文字和背景,span.toggle-btn是滑动的按钮。<labelclass="switch-btn">    <inputclass="checked-switch"type="check......