OkHttp完美封装,一行搞完外部请求

亦凉 2024-04-01 19:33 13阅读 0赞

OkHttp完美封装,一行搞完外部请求

OKHttpUtil

在Java的世界中,Http客户端之前一直是Apache家的HttpClient占据主导,但是由于此包较为庞大,API又比较难用,因此并不使用很多场景。而新兴的OkHttp、Jodd-http固然好用,但是面对一些场景时,学习成本还是有一些的。很多时候,我们想追求轻量级的Http客户端,并且追求简单易用。而OKHttp
是一套处理 HTTP 网络请求的依赖库,由 Square 公司设计研发并开源,目前可以在 Java 和 Kotlin 中使用。对于 Android App
来说,OkHttp 现在几乎已经占据了所有的网络请求操作,对于服务器端请求外部接口也是必备的选择 。针对OKHttp
OkHttpUtil做了一层封装,使Http请求变得无比简单。

OKHttpUtil 功能

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

OKHttpUtil使用

maven引入

  1. <dependency>
  2. <groupId>io.github.admin4j</groupId>
  3. <artifactId>http</artifactId>
  4. <version>0.4.0</version>
  5. </dependency>

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

GET

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

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

POST

一行代码即可搞定,当然Post请求也很简单:

  1. JSON 格式的body
  2. Response post = HttpUtil.post("https://oapi.dingtalk.com/robot/send?access_token=27f5954ab60ea8b2e431ae9101b1289c138e85aa6eb6e3940c35ee13ff8b6335", "{\"msgtype\": \"text\",\"text\": {\"content\":\"【反馈提醒】我就是我, 是不一样的烟火\"}}");
  3. System.out.println("post = " + post);
  4. form 请求
  5. Map<String, Object> formParams = new HashMap<>(16);
  6. formParams.put("username", "admin");
  7. formParams.put("password", "admin123");
  8. Response response = HttpUtil.postForm("http://192.168.1.13:9100/auth/login",
  9. formParams
  10. );
  11. System.out.println("response = " + response);

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

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

文件上传

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

下载文件

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

HttpRequest 链式请求

  1. # get
  2. Response response=HttpRequest.get("https://search.gitee.com/?skin=rec&type=repository")
  3. .queryMap("q","admin4j")
  4. .header(HttpHeaderKey.USER_AGENT,"admin4j")
  5. .execute();
  6. System.out.println("response = "+response);
  7. post form
  8. Response response=HttpRequest.get("http://192.168.1.13:9100/auth/login")
  9. .queryMap("q","admin4j")
  10. .header(HttpHeaderKey.USER_AGENT,"admin4j")
  11. .form("username","admin")
  12. .form("password","admin123")
  13. .execute();
  14. System.out.println("response = "+response);

post form 日志

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

再 Springboot 中使用

maven引入

  1. <dependency>
  2. <groupId>io.github.admin4j</groupId>
  3. <artifactId>common-http-starter</artifactId>
  4. <version>0.4.0</version>
  5. </dependency>

最新版查询 io.github.admin4j:common-http-starter

spring 版可以对 OkHttp进行个性化配置
配置详见

  1. public class HttpConfig {
  2. /**
  3. * 日志等级
  4. */
  5. private HttpLoggingInterceptor.Level loggLevel = HttpLoggingInterceptor.Level.BODY;
  6. /**
  7. * 读取超时时间,秒
  8. */
  9. private long readTimeout = 30;
  10. /**
  11. * 链接超时时间
  12. */
  13. private long connectTimeout = 30;
  14. private boolean followRedirects = false;
  15. /**
  16. * 最大的连接数
  17. */
  18. private int maxIdleConnections = 5;
  19. /**
  20. * 最大的kepAlive 时间 秒
  21. */
  22. private long keepAliveDuration = 5;
  23. private String userAgent = "OKHTTP";
  24. /**
  25. * 是否支持cookie
  26. */
  27. private boolean cookie = false;
  28. private ProxyConfig proxy;
  29. @Data
  30. public static class ProxyConfig {
  31. private Proxy.Type type = Proxy.Type.HTTP;
  32. private String host;
  33. private Integer port = 80;
  34. private String userName;
  35. private String password;
  36. }
  37. }

如何快速封装外部接口

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

  1. public class EbayClient extends ApiJsonClient {
  2. /**
  3. * 店铺配置
  4. *
  5. * @param storeId
  6. */
  7. public EbayClient(Long storeId) {
  8. //TODO 获取店铺相关配置
  9. Map<String, String> config = new HashMap<>();
  10. basePath = "https://api.ebay.com";
  11. defaultHeaderMap.put("Authorization", "Bearer " + config.get("accessToken"));
  12. defaultHeaderMap.put("X-EBAY-C-MARKETPLACE-ID", config.get("marketplaceId"));
  13. }
  14. }

EbayClient 封装ebay api请求 基础类

  1. /**
  2. * ebay 库存相关api
  3. * @author andanyang
  4. */
  5. public class EbayInventoryClient extends EbayClient {
  6. /**
  7. * 店铺配置
  8. *
  9. * @param storeId
  10. */
  11. public EbayInventoryClient(Long storeId) {
  12. super(storeId);
  13. }
  14. /**
  15. * 库存列表
  16. *
  17. * @param limit
  18. * @param offset
  19. * @return
  20. * @throws IOException
  21. */
  22. public JSONObject inventoryItem(Integer limit, Integer offset) throws IOException {
  23. Map<String, Object> queryMap = new HashMap(2);
  24. queryMap.put("limit", limit);
  25. queryMap.put("offset", offset);
  26. return get("/sell/inventory/v1/inventory_item", queryMap);
  27. }
  28. }

EbayInventoryClient 封装ebay 库存 api请求
使用

  1. EbayInventoryClient ebayInventoryClient=new EbayInventoryClient(1L);
  2. JSONObject jsonObject=ebayInventoryClient.inventoryItem(0,10);
  3. /**
  4. * 订单相关api
  5. * @author andanyang
  6. */
  7. public class EbayOrderClient extends EbayClient {
  8. /**
  9. * 店铺配置
  10. *
  11. * @param storeId
  12. */
  13. public EbayOrderClient(Long storeId) {
  14. super(storeId);
  15. }
  16. /**
  17. * 订单列表
  18. *
  19. * @param beginTime
  20. * @param endTime
  21. * @param limit
  22. * @param offset
  23. * @return
  24. */
  25. public JSONObject orders(String beginTime, String endTime, int limit, int offset) {
  26. final String path = "/sell/fulfillment/v1/order";
  27. String filter = MessageFormat.format("lastmodifieddate:[{0}..{1}]", beginTime, endTime);
  28. //
  29. Map<String, Object> queryMap = new HashMap<>(8);
  30. queryMap.put("filter", filter);
  31. queryMap.put("limit", limit);
  32. queryMap.put("offset", offset);
  33. return get("/sell/inventory/v1/inventory_item", queryMap);
  34. }
  35. }

库存相关的使用EbayInventoryClient,订单相关的使用EbayOrderClient,是不是很清晰

源码位置 github.com/admin4j/common-http

发表评论

表情:
评论列表 (有 0 条评论,13人围观)

还没有评论,来说两句吧...

相关阅读

    相关 OkHttp简单封装

    OkHttp简单封装 > 由于OkHttp访问网络需要在子线程中进行,所以每次都单独开一个子线程,非常麻烦,而且会导致代码非常臃肿非常混乱。所以这里做了一个简单的封装,使