jdk 11 自带的HttpClient

jdk 11 自带的HttpClient

文章目录

  • jdk 11 自带的HttpClient
    • 步骤1:创建jdk HttpClient 对象
    • 步骤2:创建请求
    • 步骤3:使用client.sent()发送同步请求
    • 步骤4:处理响应
    • 下面是发送post请求,请求类型是json,使用client.sent()发送**异步**请求
    • 完整示例:不用改,可以直接用
    • 武林秘籍:

jdk 11 自带的HttpClient_第1张图片

步骤1:创建jdk HttpClient 对象

 /**
     * 创建jdk HttpClient 对象
     *
     * @return
     */
    public static HttpClient getHttpClient() {
        return HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .followRedirects(HttpClient.Redirect.NORMAL)
                //连接超时时间
                .connectTimeout(Duration.ofSeconds(20))
                .proxy(ProxySelector.getDefault())
                //.executor()
                .build();
    }

步骤2:创建请求


    /**
     * 描述:创建请求
     * get请求不带参数、get请求带参数,
     * post请求不带参数、post请求带参数
     * 都可以用该方法
     *
     * @param method {@link JdkHttpClientUtil#GET,JdkHttpClientUtil#POST}
     * @param uri    请求地址
     * @param query  查询字符串 如 ie=utf-8&csq=1 或者json字符串
     * @param header 请求头数组 如:
 String[] header=new String[]
     *  {"token1Name","token1Val","token2Name","token2Val"};
     */
    public static HttpRequest getOrPostHttpRequest(String method, String uri, String query, String[] header) {
        final HttpRequest.Builder builder = HttpRequest.newBuilder().uri(URI.create(uri));
        // 判断是否有请求头参数header
        if (header != null && header.length >= 0) {
            builder.headers(header);
        }

        return
                builder
                        //判断是否有查询参数
                        .method(method, (query == null || query == "") ? HttpRequest.BodyPublishers.noBody() :
                                 HttpRequest.BodyPublishers.ofString(query, StandardCharsets.UTF_8)
                                //这两种方法都ok
                               // HttpRequest.BodyPublishers.ofByteArray(query.getBytes())
                        )
                        //读取超时时间
                        .timeout(Duration.ofMinutes(2)).build();
    }

步骤3:使用client.sent()发送同步请求

//3.发送请求
        final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));

步骤4:处理响应

        //4.处理响应
        final int statusCode = response.statusCode();
        final String responseBody = response.body();
        System.out.println("返回状态码是:" + statusCode);
        System.out.println(responseBody);

下面是发送post请求,请求类型是json,使用client.sent()发送异步请求

 //下面是发送post 请求,请求类型为json ,希望接收json
        final String uri2 = "https://www2.deepl.com/jsonrpc?method=LMT_split_text";
        String queryJson = "{\"jsonrpc\":\"2.0\",\"method\": \"LMT_split_text\",\"params\":{\"texts\":[\"followRedirects\"],\"commonJobParams\":{\"mode\":\"translate\"},\"lang\":{\"lang_user_selected\":\"EN\",\"preference\":{\"weight\":{\"DE\":0.19473,\"EN\":24.18327,\"ES\":0.1889,\"FR\":0.29868,\"IT\":0.13393,\"JA\":0.07362,\"NL\":0.36924,\"PL\":0.17236,\"PT\":0.11651,\"RU\":0.04533,\"ZH\":1.60654,\"BG\":0.0363,\"CS\":0.12581,\"DA\":0.21426,\"EL\":0.04046,\"ET\":0.14302,\"FI\":0.07996,\"HU\":0.07409,\"LT\":0.06742,\"LV\":0.04943,\"RO\":0.07113,\"SK\":0.12092,\"SL\":0.04123,\"SV\":0.29803,\"TR\":0.0578,\"ID\":0.0757,\"UK\":0.03858},\"default\":\"default\"}}},\"id\":13070003}";

        String[] header2=new String[]{"content-type","application/json","Accept", "application/json" };

        HttpRequest request2 = getOrPostHttpRequest(JdkHttpClientUtil.POST, uri2, queryJson, header2);
        //client.sendAsync 发送异步方法
        final CompletableFuture<HttpResponse<String>> future = client.sendAsync(request2, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        final HttpResponse<String> response2 = future.get();
        //4.处理响应
        final int statusCode2 = response2.statusCode();
        final String responseBody2 = response2.body();
        System.out.println("返回状态码是:" + statusCode2);
        System.out.println(responseBody2);

jdk 11 自带的HttpClient_第2张图片

完整示例:不用改,可以直接用

import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;

/**
 *  JdkHttpClientUtil 类所有的方法 都是jdk11 自带的
 *
 *  HttpRequest.BodyPublishers 用于处理请求参数,如:是以字符串传送,还是按字节
 *  HttpResponse.BodyHandlers  用于处理响应体,如:是处理成响应文本,还是处理成响应流
 *
 *  武林秘籍:https://openjdk.org/groups/net/httpclient/recipes.htm
 */
public class JdkHttpClientUtil {
    public static final String GET = "GET";
    public static final String POST = "POST";

    public static void main(String[] args) throws Exception {
        // 1. 创建jdk HttpClient 对象
        HttpClient client = getHttpClient();
        // final String uri = "https://www.baidu.com";
        // HttpRequest request = getHttpRequest(uri);

        // 2. 构建HttpRequest请求对象
        final String uri = "https://www.baidu.com/s";
        String query = "ie=utf-8&csq=1&pstg=20&mod=2&isbd=1&cqid=b6d9801e00080d0a&istc=886&ver=Rt5bJQkDOb0aje7jof0Un39Z1rBzXCmLDoO&chk=638a2e8a&isid=EF1ABC098AE51628&ie=utf-8&f=8&rsv_bp=1&tn=baidu&wd=HttpClient&ct=2097152&si=oracle.com&oq=Http%2526lt%253Blient&rsv_pq=aeab00610008ae59&rsv_t=0be6mAUUmhf6O8ehMCFN6anJ71ZkKAEAIKGmiCqHQbETtQ95Cv8pth6IPnw&rqlang=cn&rsv_enter=0&rsv_dl=tb&rsv_btype=t&bs=HttpClient&f4s=1&_ck=1886.1.86.79.22.804.37&isnop=0&rsv_stat=-2&rsv_bp=1";
        HttpRequest request = getOrPostHttpRequest(JdkHttpClientUtil.GET, uri, query, null);

        //3.发送请求
        final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        //4.处理响应
        final int statusCode = response.statusCode();
        final String responseBody = response.body();
        System.out.println("返回状态码是:" + statusCode);
        System.out.println(responseBody);

        //下面是发送post 请求,请求类型为json ,希望接收json
        final String uri2 = "https://www2.deepl.com/jsonrpc?method=LMT_split_text";
        String queryJson = "{\"jsonrpc\":\"2.0\",\"method\": \"LMT_split_text\",\"params\":{\"texts\":[\"followRedirects\"],\"commonJobParams\":{\"mode\":\"translate\"},\"lang\":{\"lang_user_selected\":\"EN\",\"preference\":{\"weight\":{\"DE\":0.19473,\"EN\":24.18327,\"ES\":0.1889,\"FR\":0.29868,\"IT\":0.13393,\"JA\":0.07362,\"NL\":0.36924,\"PL\":0.17236,\"PT\":0.11651,\"RU\":0.04533,\"ZH\":1.60654,\"BG\":0.0363,\"CS\":0.12581,\"DA\":0.21426,\"EL\":0.04046,\"ET\":0.14302,\"FI\":0.07996,\"HU\":0.07409,\"LT\":0.06742,\"LV\":0.04943,\"RO\":0.07113,\"SK\":0.12092,\"SL\":0.04123,\"SV\":0.29803,\"TR\":0.0578,\"ID\":0.0757,\"UK\":0.03858},\"default\":\"default\"}}},\"id\":13070003}";

        String[] header2=new String[]{"content-type","application/json","Accept", "application/json" };

        HttpRequest request2 = getOrPostHttpRequest(JdkHttpClientUtil.POST, uri2, queryJson, header2);
        //client.sendAsync 发送异步方法
        final CompletableFuture<HttpResponse<String>> future = client.sendAsync(request2, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        final HttpResponse<String> response2 = future.get();
        //4.处理响应
        final int statusCode2 = response2.statusCode();
        final String responseBody2 = response2.body();
        System.out.println("返回状态码是:" + statusCode2);
        System.out.println(responseBody2);

    }

    /**
     * get请求无参
     * @param uri
     * @return
     */
    public static HttpRequest getHttpRequest(String uri) {
        return HttpRequest.newBuilder()
                .uri(URI.create(uri))
                //读取超时时间
                .timeout(Duration.ofMinutes(2)).GET().build();
    }

    /**
     * 描述:创建请求
     * get请求不带参数、get请求带参数,
     * post请求不带参数、post请求带参数
     * 都可以用该方法
     *
     * @param method {@link JdkHttpClientUtil#GET,JdkHttpClientUtil#POST}
     * @param uri    请求地址
     * @param query  查询字符串 如 ie=utf-8&csq=1 或者json字符串
     * @param header 请求头数组 如:
String[] header=new String[]{"token1Name","token1Val","token2Name","token2Val"};
     *               @return
     */
    public static HttpRequest getOrPostHttpRequest(String method, String uri, String query, String[] header) {
        final HttpRequest.Builder builder = HttpRequest.newBuilder().uri(URI.create(uri));
        // 判断是否有请求头参数header
        if (header != null && header.length >= 0) {
            builder.headers(header);
        }

        return
                builder
                        //判断是否有查询参数
                        .method(method, (query == null || query == "") ? HttpRequest.BodyPublishers.noBody() :
                                 HttpRequest.BodyPublishers.ofString(query, StandardCharsets.UTF_8)
                                //这两种方法都ok
                               // HttpRequest.BodyPublishers.ofByteArray(query.getBytes())
                        )
                        //读取超时时间
                        .timeout(Duration.ofMinutes(2)).build();
    }

    /**
     * 创建jdk HttpClient 对象
     *
     * @return
     */
    public static HttpClient getHttpClient() {
        return HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .followRedirects(HttpClient.Redirect.NORMAL)
                //连接超时时间
                .connectTimeout(Duration.ofSeconds(20))
                .proxy(ProxySelector.getDefault())
                //.executor()
                .build();
    }
}

武林秘籍:

https://openjdk.org/groups/net/httpclient/recipes.htm

学到了就要教人,赚到了就要给人,开源精神,资源共享 resource sharing!

你可能感兴趣的:(java,java,jdk,11,HttpClient)