1 行のコードで Http リクエストが完了します。使いやすいです。

OKHttpUtil

Java の世界では、Apache の HttpClient が常に支配的な Http クライアントでしたが、パッケージが比較的大きく、API が使いにくいため、多くのシナリオでは使用されていません。新しい OkHttp と Jodd-http は使いやすいですが、いくつかのシナリオに直面すると、学習コストがかかります。

多くの場合、軽量の Http クライアントを追求し、シンプルさと使いやすさを追求したいと考えています。OKHttp は、HTTP ネットワーク リクエストを処理するための依存ライブラリのセットです。Square によって設計および開発されたオープン ソースです。現在、Java および Kotlin で使用できます。

Android アプリの場合、OkHttp は現在ネットワーク リクエスト操作のほとんどを占めており、外部インターフェイスへのサーバー側リクエストにも必要な選択です。OKHttp の場合、OkHttpUtil はカプセル化のレイヤーを作成し、Http リクエストを非常にシンプルにします。

OKHttpUtil 関数

  • URL に応じて HTTP を要求するか HTTPS を要求するかを自動的に判断し、冗長なコードを別途記述する必要はありません。

  • デフォルトでは、Cookie は自動的に記録されます. たとえば、シミュレートされたログインを実装できます。

  • 304 ジャンプを自動的に識別し、2 番目のリクエストを行う

  • プロキシ構成をサポート

  • リファラー構成のサポート

  • ユーザーエージェント構成をサポート

  • Gzip 形式を自動的に識別して解凍し、コンテンツを返します

  • springboot 構成ファイルのサポート

  • 最小限のカプセル化呼び出し

OKHttpUtil の使用

インポート

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

最新バージョンのクエリ:

https://search.maven.org/artifact/io.github.admin4j/http

得る

これを使用する最も簡単な方法は、HttpUtil ツール クラスを使用してインターフェイスをすばやく要求することです。

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

役職

1 行のコードで実行できます。もちろん、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);

ファイルのアップロード

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 チェーン リクエスト

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

投稿フォーム ログ

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}

スプリングブートで使用

インポート

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

最新バージョンのクエリ io.github.admin4j:common-http-starter

春のバージョンはOkHttp構成をパーソナライズできます

構成の詳細については、を参照してください。

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

外部インターフェイスをすばやくカプセル化する方法

物理的なプロジェクトを例にとると、eBay インターフェースをカプセル化します

public class EbayClient extends ApiJsonClient {

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

        //TODO 获取店铺相关配置
        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 リクエストの基本クラスをカプセル化する

/**
 * 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、非常に明確か

おすすめ

転載: blog.csdn.net/weixin_45740811/article/details/128416847