首頁 > Java > java教程 > 主體

如何使用Java內建的HttpClient發送HTTP請求?

王林
發布: 2023-04-24 20:04:05
轉載
868 人瀏覽過

1.信任憑證管理類別

package cn.wja.component;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;


class MyX509TrustManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s)  {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s)  {
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    public static TrustManager[] getTrustManagers() {
        TrustManager[] trustAllCertificates = {new MyX509TrustManager()};
        return trustAllCertificates;
    }
}
登入後複製

2.HttpClient類別

package cn.wja.component;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManager;
import java.net.http.HttpClient;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;

public class MyHttpClient {
    static public HttpClient getClient() throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustManagers = MyX509TrustManager.getTrustManagers();
        var timeoutInSeconds = 60;
        SSLParameters sslParams = new SSLParameters();
        sslParams.setEndpointIdentificationAlgorithm("");
        SSLContext sc = SSLContext.getInstance("SSL");
        //取消主机名验证
        System.setProperty("jdk.internal.httpclient.disableHostnameVerification", "true");
        sc.init(null, trustManagers, new SecureRandom());
        return HttpClient.newBuilder()
                .connectTimeout(Duration.ofMillis(timeoutInSeconds * 1000))
                .sslContext(sc)
                .sslParameters(sslParams)
                .followRedirects(HttpClient.Redirect.NEVER)
                .version(HttpClient.Version.HTTP_2)
                .build();
    }
}
登入後複製

3.傳送請求工具類別

package cn.wja.util;

import cn.wja.component.MyHttpClient;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;


import static java.nio.charset.StandardCharsets.UTF_8;

public class HttpUtils {

    public static HttpResponse<String> sendGet(String urlStr, String cookieStr) throws Exception {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("Cookie",cookieStr);
        return sendGet(urlStr,hashMap);
    }


    public static HttpResponse<String> sendGet(String urlStr, Map<String,String> headers) throws KeyManagementException, NoSuchAlgorithmException, IOException, InterruptedException {
        HttpClient client = MyHttpClient.getClient();
        HttpRequest.Builder reqBuilder = getReqBuilder(urlStr);
        reqBuilder.GET();
        for (String key:headers.keySet()){
            reqBuilder.header(key, headers.get(key));
        }
        HttpRequest request = reqBuilder.build();
        HttpResponse<String> result = client.send(request, HttpResponse.BodyHandlers.ofString(UTF_8));
        return result;
    }

    private static HttpResponse<String> sendPost(String contentType, String urlStr, String bodyStr, String cookieStr) throws Exception {
        HttpClient client = MyHttpClient.getClient();
        HttpRequest.Builder reqBuilder = getReqBuilder(urlStr);
        HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofString(bodyStr);
        reqBuilder.header("Content-Type", contentType)
                .POST(bodyPublisher)
                .header("Cookie", cookieStr);
        HttpRequest request = reqBuilder.build();
        HttpResponse<String> result = client.send(request, HttpResponse.BodyHandlers.ofString(UTF_8));
        return result;
    }
    
    public static HttpResponse<String> sendFormPost(String urlStr, String formStr, String cookieStr) throws Exception {
        return sendPost("application/x-www-form-urlencoded;charset=utf-8", urlStr, formStr, cookieStr);
    }

    public static HttpResponse<String> sendJsonPost(String urlStr, String jsonStr, String cookieStr) throws Exception {
        return sendPost("application/json;charset=utf-8", urlStr, jsonStr, cookieStr);
    }

    public static HttpRequest.Builder getReqBuilder(String urlStr) {
        return HttpRequest.newBuilder()
                .uri(URI.create(urlStr))
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:96.0) Gecko/20100101 Firefox/96.0");
    }
}
登入後複製

4.測試

如何使用Java內建的HttpClient發送HTTP請求?

#測試表明,透過呼叫工具類別方法,可以直接發送GET請求和帶有Form表單/Json的POST請求。如果您要傳送其他形式的HTTP請求,您也可以參考上述程式碼自行實作。

以上是如何使用Java內建的HttpClient發送HTTP請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:yisu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!