欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java 使用 HttpClient 發(fā)送 GET請(qǐng)求和 POST請(qǐng)求

 更新時(shí)間:2021年08月24日 11:48:47   作者:梅小西愛(ài)學(xué)習(xí)  
本文主要介紹了Java 使用 HttpClient 發(fā)送 GET請(qǐng)求和 POST請(qǐng)求,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

概述

日常工作中,我們經(jīng)常會(huì)有發(fā)送 HTTP 網(wǎng)絡(luò)請(qǐng)求的需求,概括下我們常見(jiàn)的發(fā)送 HTTP 請(qǐng)求的需求內(nèi)容:

  • 可以發(fā)送基本的 GET/POST/PUT/DELETE 等請(qǐng)求;
  • HTTP請(qǐng)求,可以附帶認(rèn)證,包括基本的 用戶(hù)名/密碼 認(rèn)證,以及 Bearer Token 認(rèn)證;
  • 請(qǐng)求可以自定義 超時(shí)時(shí)間;
  • HTTP請(qǐng)求可以帶參數(shù),也可以不帶參數(shù);
  • HTTP請(qǐng)求返回結(jié)果,可以直接傳入一個(gè) Class,這樣結(jié)果就不用二次解析;
  • 請(qǐng)求的路徑可以是 url,也可以是 Uri;

針對(duì)以上常見(jiàn)的 HTTP 請(qǐng)求,在 HttpClient 的基礎(chǔ)上做了二次封裝,可以直接簡(jiǎn)單、高效地發(fā)送HTTP請(qǐng)求。

本文所使用的的 HttpClient 版本為 4.5.3,pom依賴(lài)如下:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>

認(rèn)證方式

HTTP請(qǐng)求中,常用的認(rèn)證方式包括:

  • 用戶(hù)名 + 密碼 認(rèn)證
  • Bearer Token 認(rèn)證

其實(shí)這些認(rèn)證的本質(zhì),都是通過(guò)在 HTTP Request Header 中,添加固定的參數(shù),如下格式:

Authorization: token字符串

上面的Authorization 就是 HTTP Header 的 key,而 token字符串 就是具體的認(rèn)證方式中需要傳遞的參數(shù)。

我們將所有的認(rèn)證方式,都抽象為 Auth 類(lèi),并定義方法 getAuth 方法,由具體的子類(lèi)去實(shí)現(xiàn),返回自定義認(rèn)證方式中所需要的token字符串。

基礎(chǔ)認(rèn)證Auth

public interface Auth {

    String getAuth();
}

用戶(hù)名密碼認(rèn)證

BasicAuth,用于做用戶(hù)名和密碼認(rèn)證,代碼如下:

public class BasicAuth implements Auth {

    private String username;

    private String password;

    public BasicAuth(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @Override
    public String getAuth() {
        String auth = String.format("%s:%s", this.username, this.password);

        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
        return "Basic " + new String(encodedAuth);
    }
}

Bearer Token 認(rèn)證

BearerAuth,用于做 Bearer Token認(rèn)證,代碼如下:

public class BearerAuth implements Auth {

    private String token;

    public BearerAuth(String token) {
        this.token = token;
    }

    @Override
    public String getAuth() {
        return "Bearer " + this.token;
    }
}

上面介紹了兩種常用的認(rèn)證方式,如果有其他的認(rèn)證方式,實(shí)現(xiàn) Auth 接口的 getAuth 方法即可。

這個(gè) Auth 我們會(huì)在真正發(fā)送 HTTP 請(qǐng)求時(shí)用到。

配置超時(shí)

HttpClient中,通過(guò) setDefaultRequestConfig 來(lái)設(shè)置請(qǐng)求的參數(shù)配置,包括請(qǐng)求超時(shí)時(shí)間等。

生成 RequestConfig

/**
 * 設(shè)置 HTTP 請(qǐng)求超時(shí)時(shí)間
 *
 * @param connectTimeout tcp 連接超時(shí)時(shí)間
 * @param readTimeout    讀取數(shù)據(jù)超時(shí)時(shí)間
 * @return
 */
private RequestConfig getRequestConfig(int connectTimeout, int readTimeout) {
    return RequestConfig.custom()
            .setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectTimeout)
            .setSocketTimeout(readTimeout)
            .build();
}

設(shè)置超時(shí)時(shí)間

HttpClientBuilder.create()
        .setDefaultRequestConfig(requestConfig)
        .build();

到這里,HttpClient所需要做的一些配置,基本就結(jié)束了,下面將展示完整的代碼示例。

完整代碼 HttpRequestClient

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wxweven
 */
@Slf4j
public class HttpRequestClient {

    // 默認(rèn) 連接/讀取數(shù)據(jù) 超時(shí)時(shí)間都是 10s
    private static final int DEFAULT_CONNECT_TIMEOUT = 10_000;
    private static final int DEFAULT_READ_TIMEOUT = 10_000;
    private static final Gson GSON = new Gson();

    private Auth auth;
    private HttpClient httpClient;

    // 用戶(hù)名密碼認(rèn)證,默認(rèn)的超時(shí)時(shí)間(10s)
    public HttpRequestClient(String username, String password) {
        this(username, password,
                DEFAULT_CONNECT_TIMEOUT,
                DEFAULT_READ_TIMEOUT
        );
    }

    // 用戶(hù)名密碼認(rèn)證,自定義超時(shí)時(shí)間
    public HttpRequestClient(String username, String password,
                               int connectTimeout, int readTimeout) {

        this.auth = new BasicAuth(username, password);
        this.httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(getRequestConfig(connectTimeout, readTimeout))
                .build();
    }

    // BearerToken 認(rèn)證,默認(rèn)的超時(shí)時(shí)間(10s)
    public HttpRequestClient(String bearerToken) {
        this(bearerToken,
                DEFAULT_CONNECT_TIMEOUT,
                DEFAULT_READ_TIMEOUT
        );
    }

    // BearerToken 認(rèn)證,自定義超時(shí)時(shí)間
    public HttpRequestClient(String bearerToken,
                               int connectTimeout, int readTimeout) {

        this.auth = new BearerAuth(bearerToken);
        this.httpClient = HttpClientBuilder.create()
                .setDefaultRequestConfig(getRequestConfig(connectTimeout, readTimeout))
                .build();
    }

    /**
     * 設(shè)置 HTTP 請(qǐng)求超時(shí)時(shí)間
     *
     * @param connectTimeout tcp 連接超時(shí)時(shí)間
     * @param readTimeout    讀取數(shù)據(jù)超時(shí)時(shí)間
     * @return
     */
    private RequestConfig getRequestConfig(int connectTimeout, int readTimeout) {
        return RequestConfig.custom()
                .setConnectTimeout(connectTimeout)
                .setConnectionRequestTimeout(connectTimeout)
                .setSocketTimeout(readTimeout)
                .build();
    }

    /**
     * 發(fā)送 GET 請(qǐng)求,不帶參數(shù)
     *
     * @param url
     * @return
     */
    public String doGet(String url) {
        return doGet(url, new HashMap<>());
    }

    /**
     * 發(fā)送 GET 請(qǐng)求,不帶參數(shù)
     *
     * @param uri
     * @return
     */
    public String doGet(URI uri) {
        return doGet(uri, new HashMap<>());
    }

    /**
     * 發(fā)送 GET 請(qǐng)求,K-V 形式參數(shù)
     *
     * @param url
     * @param params
     * @return
     */
    public String doGet(String url, Map<String, String> params) {
        RequestBuilder reqBuilder = RequestBuilder.get(url);
        return doGet(reqBuilder, params);
    }

    /**
     * 發(fā)送 GET 請(qǐng)求,K-V 形式參數(shù)
     *
     * @param uri
     * @param params
     * @return
     */
    public String doGet(URI uri, Map<String, String> params) {
        RequestBuilder reqBuilder = RequestBuilder.get(uri);
        return doGet(reqBuilder, params);
    }

    public String doGet(RequestBuilder reqBuilder, Map<String, String> params) {
        reqBuilder.addHeader(HttpHeaders.AUTHORIZATION, auth.getAuth());

        for (Map.Entry<String, String> entry : params.entrySet()) {
            reqBuilder.addParameter(entry.getKey(), entry.getValue());
        }

        try {
            HttpResponse resp = httpClient.execute(reqBuilder.build());
            return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("doGet 異常: reqBuilder={}, params={}", reqBuilder, params, e);
            return null;
        }
    }

    /***
     * 發(fā)送 GET 請(qǐng)求,不帶參數(shù),返回指定類(lèi)型的 class
     * @param url 請(qǐng)求的 url
     * @param responseType 返回類(lèi)型
     * @param <T>
     * @return
     */
    public <T> T getForObject(String url, Class<T> responseType) {
        RequestBuilder reqBuilder = RequestBuilder.get(url);
        return getForObject(reqBuilder, responseType);
    }

    /***
     * 發(fā)送 GET 請(qǐng)求,不帶參數(shù),返回指定類(lèi)型的 class
     * @param uri 請(qǐng)求的 uri
     * @param responseType 返回類(lèi)型
     * @param <T>
     * @return
     */
    public <T> T getForObject(URI uri, Class<T> responseType) {
        RequestBuilder reqBuilder = RequestBuilder.get(uri);
        return getForObject(reqBuilder, responseType);
    }

    public <T> T getForObject(RequestBuilder reqBuilder, Class<T> responseType) {
        reqBuilder.addHeader(HttpHeaders.AUTHORIZATION, auth.getAuth());

        try {
            HttpResponse resp = httpClient.execute(reqBuilder.build());
            String result = EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);

            return GSON.fromJson(result, responseType);
        } catch (IOException e) {
            log.error("getForObject 異常: reqBuilder={}, responseType={}", reqBuilder, responseType, e);
            return null;
        }
    }

    /**
     * 發(fā)送 POST 請(qǐng)求,JSON 形式
     *
     * @param url
     * @param json json字符串
     * @return
     */
    public String doPost(String url, String json) {
        try {
            HttpResponse resp = this.exchange(HttpMethod.POST, url, json);
            return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("doPost 異常: url={}, json={}", url, json, e);
            return null;
        }
    }

    /**
     * 發(fā)送 POST 請(qǐng)求,JSON 形式,返回 HttpResponse
     *
     * @param url
     * @param json json字符串
     * @return
     */
    public HttpResponse doPostResp(String url, String json) {
        return this.exchange(HttpMethod.POST, url, json);
    }

    /**
     * 發(fā)送 PUT 請(qǐng)求,JSON 形式
     *
     * @param url
     * @param json json字符串
     * @return
     */
    public HttpResponse doPut(String url, String json) {
        return this.exchange(HttpMethod.PUT, url, json);
    }

    /**
     * 發(fā)送 PUT 請(qǐng)求,JSON 形式
     *
     * @param url
     * @param json json字符串
     * @return
     */
    public HttpResponse doDelete(String url, String json) {
        return this.exchange(HttpMethod.DELETE, url, json);
    }

    public HttpResponse exchange(HttpMethod method, String url, String json) {
        RequestBuilder reqBuilder = RequestBuilder.create(method.toString())
                .setUri(url)
                .addHeader(HttpHeaders.AUTHORIZATION, auth.getAuth())
                .addHeader("Accept", ContentType.APPLICATION_JSON.toString())
                .addHeader("Content-type", ContentType.APPLICATION_JSON.toString());

        if (StringUtils.isNotBlank(json)) {
            reqBuilder.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
        }

        try {
            return httpClient.execute(reqBuilder.build());
        } catch (IOException e) {
            log.error("doPost 異常: url={}, json={}", url, json, e);
            return null;
        }
    }
}

到此這篇關(guān)于Java 使用 HttpClient 發(fā)送 GET請(qǐng)求和 POST請(qǐng)求的文章就介紹到這了,更多相關(guān)Java HttpClient GET請(qǐng)求和 POST請(qǐng)求內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 初識(shí)Spring Boot框架和快速入門(mén)

    初識(shí)Spring Boot框架和快速入門(mén)

    這篇文章主要介紹了初識(shí)Spring Boot框架學(xué)習(xí),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-04-04
  • Java程序命令行參數(shù)用法總結(jié)

    Java程序命令行參數(shù)用法總結(jié)

    這篇文章主要介紹了Java程序命令行參數(shù)用法總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • 簡(jiǎn)單實(shí)現(xiàn)Java web服務(wù)器

    簡(jiǎn)單實(shí)現(xiàn)Java web服務(wù)器

    這篇文章主要為大家詳細(xì)介紹了簡(jiǎn)單實(shí)現(xiàn)Java web服務(wù)器的詳細(xì)步驟,感興趣的小伙伴們可以參考一下
    2016-06-06
  • SpringBoot 設(shè)置傳入?yún)?shù)非必要的操作

    SpringBoot 設(shè)置傳入?yún)?shù)非必要的操作

    這篇文章主要介紹了SpringBoot 設(shè)置傳入?yún)?shù)非必要的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-02-02
  • MyBatisPlus的IService接口實(shí)現(xiàn)

    MyBatisPlus的IService接口實(shí)現(xiàn)

    MyBatisPlus是一個(gè)為MyBatis提供增強(qiáng)的工具,它通過(guò)IService接口簡(jiǎn)化了數(shù)據(jù)庫(kù)的CRUD操作,IService接口封裝了一系列常用的數(shù)據(jù)操作方法,本文就來(lái)介紹一下,感興趣的可以了解一下
    2024-10-10
  • java使用TimeZone將中國(guó)標(biāo)準(zhǔn)時(shí)間轉(zhuǎn)成時(shí)區(qū)值

    java使用TimeZone將中國(guó)標(biāo)準(zhǔn)時(shí)間轉(zhuǎn)成時(shí)區(qū)值

    這篇文章主要介紹了java使用TimeZone將中國(guó)標(biāo)準(zhǔn)時(shí)間轉(zhuǎn)成時(shí)區(qū)值的相關(guān)資料,需要的朋友可以參考下
    2023-11-11
  • spring mvc中@RequestBody注解的作用說(shuō)明

    spring mvc中@RequestBody注解的作用說(shuō)明

    這篇文章主要介紹了spring mvc中@RequestBody注解的作用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • Java實(shí)戰(zhàn)之城市多音字處理

    Java實(shí)戰(zhàn)之城市多音字處理

    這篇文章主要介紹了Java實(shí)戰(zhàn)之城市多音字處理,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04
  • SpringBoot整合flyway實(shí)現(xiàn)步驟解析

    SpringBoot整合flyway實(shí)現(xiàn)步驟解析

    這篇文章主要介紹了SpringBoot整合flyway實(shí)現(xiàn)步驟解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • JPA如何使用findBy方法自定義查詢(xún)

    JPA如何使用findBy方法自定義查詢(xún)

    這篇文章主要介紹了JPA如何使用findBy方法自定義查詢(xún),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11

最新評(píng)論