栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

WebClient网络请求工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

WebClient网络请求工具类

网络请求工具类:

package com.xx.xx.xx.helper;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelOption;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.http.MediaType;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.util.linkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


public class WebClientHelper {

    private static final Integer DEFAULT_CONNECT_TIMEOUT = 3000;

    private static final Integer DEFAULT_REQUEST_TIMEOUT = 10000;

    
    public static ClientResponse getResponse(String url) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts()
                .get()
                .uri(url)
                .exchange();

        return resp.block();
    }

    
    public static  T get(String url, Class tClass, Map headers) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts()
                .get()
                .uri(url)
                .headers(t -> t.setAll(headers))
                .retrieve()
                .bodyToMono(tClass).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));
        return resp.block();
    }

    
    public static String get(String url, Map headers) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts()
                .get()
                .uri(url)
                .headers(t -> t.setAll(headers))
                .retrieve()
                .bodyToMono(String.class).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));
        return resp.block();
    }

    
    public static String get(String scheme, String host, String path, Object obj, Map headers) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts()
                .get()
                .uri(uriBuilder -> uriBuilder.scheme(scheme).host(host).path(path).queryParams(getRequestParamMapByObj(obj)).build())
                .headers(t -> t.setAll(headers))
                .retrieve()
                .bodyToMono(String.class).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));
        return resp.block();
    }

    
    public static  T get(String url, Object obj, Class tClass) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts()
                .get()
                .uri(uriBuilder -> uriBuilder.path(url).queryParams(getRequestParamMapByObj(obj)).build())
                .retrieve()
                .bodyToMono(tClass).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));
        return resp.block();
    }


    
    public static  T get(String url, Class tClass) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(tClass).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));
        return resp.block();
    }

    
    public static String get(String url) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));

        return resp.block();
    }

    
    public static  T post(String url, Map params, Class tClass) {
        MultiValueMap formData = getRequestParamMap(params);
        Mono resp = createWebClientWithConnectAndReadTimeOuts().post()
                .uri(url)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .body(BodyInserters.fromFormData(formData))
                .retrieve().bodyToMono(tClass).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));

        return resp.block();
    }

    
    public static String post(String url, Map params) {
        MultiValueMap formData = getRequestParamMap(params);
        Mono resp = createWebClientWithConnectAndReadTimeOuts().post()
                .uri(url)
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .body(BodyInserters.fromFormData(formData))
                .retrieve().bodyToMono(String.class).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));

        return resp.block();
    }

    
    public static  T postJson(String url, Object jsonBody, Class tClass) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts().post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(Mono.just(jsonBody), Object.class)
                .retrieve().bodyToMono(tClass).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));

        return resp.block();
    }

    
    public static  T postJson(String url, Map headers, Object jsonBody, Class tClass) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts().post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .headers(t -> t.setAll(headers))
                .body(Mono.just(jsonBody), Object.class)
                .retrieve().bodyToMono(tClass).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));

        return resp.block();
    }

    
    public static String postJson(String url, Object jsonBody) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts().post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(Mono.just(jsonBody), Object.class)
                .retrieve().bodyToMono(String.class).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));

        return resp.block();
    }

    
    public static String postJson(String url, Map headers, Object jsonBody) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts().post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .headers(t -> t.setAll(headers))
                .body(Mono.just(jsonBody), Object.class)
                .retrieve().bodyToMono(String.class).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));

        return resp.block();
    }

    public static  T postRawJson(String url, String jsonBody, Class tClass) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts().post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(jsonBody))
                .retrieve().bodyToMono(tClass).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));

        return resp.block();
    }

    public static String postRawJson(String url, String jsonBody) {
        Mono resp = createWebClientWithConnectAndReadTimeOuts().post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(jsonBody))
                .retrieve().bodyToMono(String.class).timeout(Duration.ofMillis(DEFAULT_REQUEST_TIMEOUT));

        return resp.block();
    }

    private static WebClient createWebClientWithConnectAndReadTimeOuts() {
        // create reactor netty HTTP client
        HttpClient httpClient = HttpClient.create()
                .tcpConfiguration(tcpClient -> {
                    tcpClient = tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, DEFAULT_CONNECT_TIMEOUT);
                    tcpClient = tcpClient.doonConnected(conn -> conn
                            .addHandlerLast(new ReadTimeoutHandler(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS)));
                    return tcpClient;
                });
        // create a client http connector using above http client
        ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient);
        // use this configured http connector to build the web client
        return WebClient.builder().clientConnector(connector).build();
    }

    private static MultiValueMap getRequestParamMap(Map params) {
        MultiValueMap queryParams = new linkedMultiValueMap<>();
        for (Map.Entry entry : params.entrySet()) {
            queryParams.add(entry.getKey(), entry.getValue());
        }

        return queryParams;
    }

    private static MultiValueMap getRequestParamMapByObj(Object obj) {
        ObjectMapper objectMapper = new ObjectMapper();
        Map map = objectMapper.convertValue(obj, new TypeReference>() {
        });
        MultiValueMap queryParams = new linkedMultiValueMap<>();
        for (Map.Entry entry : map.entrySet()) {
            if (Objects.isNull(entry.getValue())) {
                continue;
            }
            queryParams.add(entry.getKey(), String.valueOf(entry.getValue()));
        }

        return queryParams;
    }


}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/434963.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号