<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          一行代碼搞定Java中Http請(qǐng)求,強(qiáng)得離譜~

          共 12548字,需瀏覽 26分鐘

           ·

          2023-02-04 18:40

          程序員的成長(zhǎng)之路
          互聯(lián)網(wǎng)/程序員/技術(shù)/資料共享 
          關(guān)注


          閱讀本文大概需要 5.5 分鐘。

          來(lái)自:andyoung.blog.csdn.net/article/details/127755025

          在Java的世界中,Http客戶端之前一直是Apache家的HttpClient占據(jù)主導(dǎo),但是由于此包較為龐大,API又比較難用,因此并不使用很多場(chǎng)景。而新興的OkHttp、Jodd-http固然好用,但是面對(duì)一些場(chǎng)景時(shí),學(xué)習(xí)成本還是有一些的。
          很多時(shí)候,我們想追求輕量級(jí)的Http客戶端,并且追求簡(jiǎn)單易用。而OKHttp是一套處理 HTTP 網(wǎng)絡(luò)請(qǐng)求的依賴庫(kù),由 Square 公司設(shè)計(jì)研發(fā)并開(kāi)源,目前可以在 Java 和 Kotlin 中使用。
          對(duì)于 Android App來(lái)說(shuō),OkHttp 現(xiàn)在幾乎已經(jīng)占據(jù)了所有的網(wǎng)絡(luò)請(qǐng)求操作,對(duì)于服務(wù)器端請(qǐng)求外部接口也是必備的選擇 。針對(duì)OKHttp,OkHttpUtil做了一層封裝,使Http請(qǐng)求變得無(wú)比簡(jiǎn)單。

          OKHttpUtil 功能

          • 根據(jù)URL自動(dòng)判斷是請(qǐng)求HTTP還是HTTPS,不需要單獨(dú)寫多余的代碼。
          • 默認(rèn)情況下Cookie自動(dòng)記錄,比如可以實(shí)現(xiàn)模擬登錄,即第一次訪問(wèn)登錄URL后后續(xù)請(qǐng)求就是登錄狀態(tài)。
          • 自動(dòng)識(shí)別304跳轉(zhuǎn)并二次請(qǐng)求
          • 支持代理配置
          • 支持referer配置
          • 支持User-Agent配置
          • 自動(dòng)識(shí)別并解壓Gzip格式返回內(nèi)容
          • 支持springboot 配置文件
          • 極簡(jiǎn)的封裝調(diào)用

          OKHttpUtil使用

          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

          GET

          最簡(jiǎn)單的使用莫過(guò)于用HttpUtil工具類快速請(qǐng)求某個(gè)接口:
          Response response = HttpUtil.get("https://github.com/search", Pair.of("q""okhttp"));
          System.out.println("response = " + response);

          POST

          一行代碼即可搞定,當(dāng)然Post請(qǐng)求也很簡(jiǎn)單:
          # 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 請(qǐng)求
          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 自動(dòng)返回JsonObject
          JSONObject object=HttpJsonUtil.get("https://github.com/search",
          Pair.of("q","http"),
          Pair.of("username","agonie201218"));
          System.out.println("object = "+object);

          文件上傳

          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/");

          HttpRequest 鏈?zhǔn)秸?qǐng)求

          # 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);
          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}

          在 Springboot 中使用

          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 版可以對(duì) OkHttp進(jìn)行個(gè)性化配置
          配置詳見(jiàn)
          public class HttpConfig {
              /**
               * 日志等級(jí)
               */

              private HttpLoggingInterceptor.Level loggLevel = HttpLoggingInterceptor.Level.BODY;

              /**
               * 讀取超時(shí)時(shí)間,秒
               */

              private long readTimeout = 30;
              /**
               * 鏈接超時(shí)時(shí)間
               */

              private long connectTimeout = 30;

              private boolean followRedirects = false;

              /**
               * 最大的連接數(shù)
               */

              private int maxIdleConnections = 5;

              /**
               * 最大的kepAlive 時(shí)間 秒
               */

              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;
              }
          }

          如何快速封裝外部接口

          以實(shí)體項(xiàng)目為例,封裝 ebay接口
          public class EbayClient extends ApiJsonClient {

              /**
               * 店鋪配置
               *
               * @param storeId
               */

              public EbayClient(Long storeId) {

                  //TODO 獲取店鋪相關(guān)配置
                  Map<String, String> config = new HashMap<>();

                  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請(qǐng)求 基礎(chǔ)類
          /**
           * ebay 庫(kù)存相關(guān)api
           * @author andanyang
           */

          public class EbayInventoryClient extends EbayClient {

              /**
               * 店鋪配置
               *
               * @param storeId
               */

              public EbayInventoryClient(Long storeId) {
                  super(storeId);
              }

              /**
               * 庫(kù)存列表
               *
               * @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 庫(kù)存 api請(qǐng)求
          使用
          EbayInventoryClient ebayInventoryClient=new EbayInventoryClient(1L);
          JSONObject jsonObject=ebayInventoryClient.inventoryItem(0,10);
          /**
           * 訂單相關(guān)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);
              }
          }
          庫(kù)存相關(guān)的使用EbayInventoryClient,訂單相關(guān)的使用EbayOrderClient,是不是很清晰。
          <END>

          推薦閱讀:

          偷偷爆料下各公司年終獎(jiǎng)!(最新版)

          這 10 幾個(gè),高級(jí)開(kāi)發(fā)用的 Git 命令,個(gè)個(gè)驚艷!

          互聯(lián)網(wǎng)初中高級(jí)大廠面試題(9個(gè)G)

          內(nèi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬(wàn)并發(fā)、消息隊(duì)列、高性能緩存、反射、Spring全家桶原理、微服務(wù)、Zookeeper......等技術(shù)棧!

          ?戳閱讀原文領(lǐng)取!                                  朕已閱 

          瀏覽 29
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  成人三级片网址 | 中文人妻无码一区二区三区不卡 | 国产又粗又硬又黄的视频 | 日韩A片一级无码免费 蜜桃 | 不卡无码免费 |