首页 > 其他分享 >OKHttpUtil使用讲解

OKHttpUtil使用讲解

时间:2022-12-28 10:12:29浏览次数:56  
标签:OKHttpUtil github http 讲解 private admin4j 使用 put response

目录

1 OKHttpUtil

1.1 引言

Java的世界中,Http客户端之前一直是Apache家的HttpClient占据主导,但是由于此包较为庞大,API又比较难用,因此并不使用很多场景。而新兴的OkHttpJodd-http固然好用,但是面对一些场景时,学习成本还是有一些的。

很多时候,我们想追求轻量级的Http客户端,并且追求简单易用。而OKHttp是一套处理 HTTP 网络请求的依赖库,由 Square 公司设计研发并开源,目前可以在 Java 和 Kotlin 中使用。

对于 Android App来说,OkHttp 现在几乎已经占据了所有的网络请求操作,对于服务器端请求外部接口也是必备的选择 。针对OKHttpOkHttpUtil做了一层封装,使Http请求变得无比简单

1.2 OKHttpUtil功能

OKHttpUtil功能:

  • 根据URL自动判断是请求HTTP还是HTTPS,不需要单独写多余的代码。
  • 默认情况下Cookie自动记录,比如可以实现模拟登录,即第一次访问登录 URL后后续请求就是登录状态。
  • 自动识别304跳转并二次请求
  • 支持代理配置
  • 支持referer配置
  • 支持User-Agent配置
  • 自动识别并解压Gzip格式返回内容
  • 支持springboot 配置文件
  • 极简的封装调用

1.3 OKHttpUtil使用

1.3.1 maven引入

<dependency>
    <groupId>io.github.admin4j</groupId>
    <artifactId>http</artifactId>
    <version>0.4.0</version>
</dependency>

最新版查询:https://search.maven.org/artifact/io.github.admin4j/http

1.3.2 GET

最简单的使用莫过于用HttpUtil工具类快速请求某个接口:

Response response = HttpUtil.get(https://github.com/search, Pair.of(q, okhttp));
System.out.println(response =  + response);

1.3.3 POST

一行代码即可搞定,当然Post请求也很简单:
JSON 格式的body


Response post = HttpUtil.post(https://oapi.dingtalk.com/robot/send?access_token=27f5954ab60ea8b2e431ae9101b1289c138e85aa6eb6e3940c35ee13ff8b6335, {\msgtype\: \text\,\text\: {\content\:\【反馈提醒】我就是我, 是不一样的烟火\}});
System.out.println("post = "+ post);

form 请求

Map<String, Object> formParams = new HashMap<>(16);
formParams.put(username, admin);
formParams.put(password, admin123);
Response response = HttpUtil.postForm(http://192.168.1.13:9100/auth/login,formParams);
System.out.println("response = "+ response);

返回格式为JSON的,可以使用 HttpJsonUtil 自动返回JsonObject

JSONObject object=HttpJsonUtil.get(https://github.com/search,
Pair.of(q,http),
Pair.of(username,agonie201218));
System.out.println("object = "+object);

1.3.4 文件上传与下载

文件上传

File file=new File(C:\\Users\\andanyang\\Downloads\\Sql.txt);
Map<String, Object> formParams=new HashMap<>();
formParams.put(key,test);
formParams.put(file,file);
formParams.put(token,WXyUseb-D4sCum-EvTIDYL-mEehwDtrSBg-Zca7t:qgOcR2gUoKmxt-VnsNb657Oatzo=:eyJzY29wZSI6InpoYW56aGkiLCJkZWFkbGluZSI6MTY2NTMwNzUxNH0=);
Response response=HttpUtil.upload(https://upload.qiniup.com/,formParams);
System.out.println(response);

文件下载

HttpUtil.down(https://gitee.com/admin4j/common-http,path/);

1.3.5 HttpRequest 链式请求

get

Response response = 
	 HttpRequest.get(https://search.gitee.com/?skin=rec&type=repository)
	.queryMap(q,admin4j)
	.header(HttpHeaderKey.USER_AGENT,admin4j)
	.execute();
System.out.println("response = "+ response);

post form

Response response = 
	HttpRequest.get(http://192.168.1.13:9100/auth/login)
	.queryMap(q,admin4j)
	.header(HttpHeaderKey.USER_AGENT,admin4j)
	.form(username,admin)
	.form(password,admin123)
	.execute();
System.out.println("response = "+response);

1.3.6 post form日志

16:49:14.092[main]DEBUG io.github.admin4j.http.core.HttpLogger- -->GET http://192.168.1.13:9100/auth/login?q=admin4j http/1.1
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger-User-Agent:admin4j
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger-Host:192.168.1.13:9100
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger-Connection:Keep-Alive
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger-Accept-Encoding:gzip
16:49:14.094[main]DEBUG io.github.admin4j.http.core.HttpLogger- -->END GET
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-<--200OK http://192.168.1.13:9100/auth/login?q=admin4j (575ms)
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-transfer-encoding:chunked
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Origin
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Access-Control-Request-Method
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Access-Control-Request-Headers
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Origin
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Access-Control-Request-Method
16:49:14.670[main]DEBUG io.github.admin4j.http.core.HttpLogger-Vary:Access-Control-Request-Headers
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-Content-Type:application/json;charset=utf-8
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-Date:Tue,08Nov 2022 08:49:14GMT
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-{code:406,msg:Full authentication is required to access this resource}
16:49:14.671[main]DEBUG io.github.admin4j.http.core.HttpLogger-<--END HTTP(76-byte body)
response=Response{protocol=http/1.1,code=200,message=OK,url=http://192.168.1.13:9100/auth/login?q=admin4j}

1.4 在 Springboot 中使用

1.4.1 maven引入

<dependency>
    <groupId>io.github.admin4j</groupId>
    <artifactId>common-http-starter</artifactId>
    <version>0.4.0</version>
</dependency>

最新版查询 io.github.admin4j:common-http-starter
spring 版可以对 OkHttp进行个性化配置

1.4.2 配置

public class HttpConfig {
    /**
     * 日志等级
     */
    private HttpLoggingInterceptor.Level loggLevel = HttpLoggingInterceptor.Level.BODY;
    /**
     * 读取超时时间,秒
     */
    private long readTimeout = 30;
    /**
     * 链接超时时间
     */
    private long connectTimeout = 30;

    private boolean followRedirects = false;
   /**
     * 最大的连接数
     */
    private int maxIdleConnections = 5;
    /**
     * 最大的kepAlive 时间 秒
     */
    private long keepAliveDuration = 5;

    private String userAgent = OKHTTP;
    /**
     * 是否支持cookie
     */
    private boolean cookie = false;
    private ProxyConfig proxy;
    
    @Data
    public static class ProxyConfig {
        private Proxy.Type type = Proxy.Type.HTTP;
        private String host;
        private Integer port = 80;
        private String userName;
        private String password;
    }
}

1.4.3 快速封装外部接口

以实体项目为例,封装 ebay接口

public class EbayClient extends ApiJsonClient {
    /**
     * 店铺配置
     *
     * @param storeId
     */
    public EbayClient(Long storeId) {

        //TODO 获取店铺相关配置
        Map<String, String> config = new HashMap<>();

        String basePath = "https://api.ebay.com";
        defaultHeaderMap.put(Authorization, Bearer  + config.get(accessToken));
        defaultHeaderMap.put(X-EBAY-C-MARKETPLACE-ID, config.get(marketplaceId));
    }
}

EbayClient 封装ebay api请求 基础类

/**
 * ebay 库存相关api
 * @author andanyang
 */
public class EbayInventoryClient extends EbayClient {

    /**
     * 店铺配置
     *
     * @param storeId
     */
    public EbayInventoryClient(Long storeId) {
        super(storeId);
    }

    /**
     * 库存列表
     *
     * @param limit
     * @param offset
     * @return
     * @throws IOException
     */
    public JSONObject inventoryItem(Integer limit, Integer offset) throws IOException {

        Map<String, Object> queryMap = new HashMap(2);
        queryMap.put(limit, limit);
        queryMap.put(offset, offset);
        return get(/sell/inventory/v1/inventory_item, queryMap);
    }
}

EbayInventoryClient 封装ebay 库存 api请求

使用

EbayInventoryClient ebayInventoryClient=new EbayInventoryClient(1L);
JSONObject jsonObject=ebayInventoryClient.inventoryItem(0,10);
/**
 * 订单相关api
 * @author andanyang
 */
public class EbayOrderClient extends EbayClient {


    /**
     * 店铺配置
     *
     * @param storeId
     */
    public EbayOrderClient(Long storeId) {
        super(storeId);
    }

    /**
     * 订单列表
     *
     * @param beginTime
     * @param endTime
     * @param limit
     * @param offset
     * @return
     */
    public JSONObject orders(String beginTime, String endTime, int limit, int offset) {

        final String path = /sell/fulfillment/v1/order;

        String filter = MessageFormat.format(lastmodifieddate:[{0}..{1}], beginTime, endTime);

        //
        Map<String, Object> queryMap = new HashMap<>(8);
        queryMap.put(filter, filter);
        queryMap.put(limit, limit);
        queryMap.put(offset, offset);

        return get(/sell/inventory/v1/inventory_item, queryMap);
    }
}

库存相关的使用EbayInventoryClient,订单相关的使用EbayOrderClient

转载于:https://mp.weixin.qq.com/s/FxnAJrIw7eXeDkhxK2S9zA

标签:OKHttpUtil,github,http,讲解,private,admin4j,使用,put,response
From: https://www.cnblogs.com/jingzh/p/17009500.html

相关文章

  • 使用kubeadm安装k8s集群(v1.20.9)
    一、安装环境系统:[root@master1~]#cat/etc/redhat-releaseCentOSLinuxrelease7.9.2009(Core)[root@master1~]#uname-aLinuxmaster13.10.0-1160.el7.x86_64#1......
  • Java 提供给第三方使用接口方法
    前言相信有很多小伙伴,在日常的开发中都有遇到过需要调用第三方接口的需求吧,但是自己有没有写过接口提供给第三方使用呢,常规的都是我们调用别人的接口,但是自己需要开发接口提......
  • 字节流使用指南
    一切皆为字节一切文件数据(文本、图片、视频等)在存储时,都是以二进制数字的形式保存,都一个一个的字节,那么传输时一样如此。所以,字节流可以传输任意文件数据。在操作流的时......
  • 企业使用无代码开发平台会有哪些优势
    无代码开发平台的核心是计算机编程语言,这是目前最先进的软件快速开发方式之一。业务人员(而不是技术人员)也可以轻松控制软件开发过程,只需在开发后台配置即可完成软件开发......
  • 面试官问:为啥不建议使用 Select *?请你大声地回答他!!
    作者:小目标青年来源:https://blog.csdn.net/qq_35387940/article/details/125921218前言不建议使用select*这几个字眼,做开发的都不陌生吧。阿里的开发手册上面也......
  • Vuex的简单使用,基于Vue2
    模仿他的,项目地址https://github.com/iamshaunjp/vuex-playlist视频地址https://www.youtube.com/watch?v=BGAu__J4xoc&list=PL4cUxeGkcC9i371QO_Rtkl26MwtiJ30P2&index......
  • Loki Promtail 使用 multiline 对Java 堆栈日志进行多行处理的示例
    promtail使用multiline处理java多行日志文本的示例Environment:promtail_version:v2.7.1originJavalogcontent:logfilecontentstdout-a.log:2022-Dec-270......
  • CompletableFuture 使用总结
    转载请注明出处:1.Future使用对比Future表示一个异步计算的结果。它提供了isDone()来检测计算是否已经完成,并且在计算结束后,可以通过get()方法来获取计算结果。在异步......
  • React项目中使用装饰器报错
    在初次使用React的装饰器时,第一次在项目中使用@会报错,原因是react默认是不支持装饰器的,所以才会报错,所以是需要做一些配置来支持装饰器。安装插件yarnadd-Drea......
  • 【数据预处理】基于Kettle的字符串数据清洗、Kettle的字段清洗、Kettle的使用参照表集
    一.前言需要本文章的源文件下链接自取:【ktr源文件】1.1实验内容本次实验内容如下:掌握基于Kettle的字符串数据清洗掌握基于Kettle的字段清洗掌握基于Kettle的使......