IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> httpclient5 工具封装 -> 正文阅读

[网络协议]httpclient5 工具封装

配置类

package com.vivo.httpclient52;

import javafx.util.Pair;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
import org.apache.hc.client5.http.classic.ExecChainHandler;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.impl.ChainElement;
import org.apache.hc.client5.http.impl.auth.CredentialsProviderBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.socket.ConnectionSocketFactory;
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.config.CharCodingConfig;
import org.apache.hc.core5.http.config.Http1Config;
import org.apache.hc.core5.http.config.Registry;
import org.apache.hc.core5.http.config.RegistryBuilder;
import org.apache.hc.core5.http.impl.io.DefaultHttpRequestWriterFactory;
import org.apache.hc.core5.http.impl.io.DefaultHttpResponseParserFactory;
import org.apache.hc.core5.http.io.HttpMessageParserFactory;
import org.apache.hc.core5.http.io.HttpMessageWriterFactory;
import org.apache.hc.core5.http.io.SocketConfig;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.apache.hc.core5.http.ssl.TLS;
import org.apache.hc.core5.pool.PoolConcurrencyPolicy;
import org.apache.hc.core5.pool.PoolReusePolicy;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

public class HttpClientConfigUtils {

    private HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    private HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory();
    private HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
    private CharCodingConfig charCodingConfig = CharCodingConfig.DEFAULT;
    private Http1Config h1Config = Http1Config.DEFAULT;
    private SSLContext sslcontext = SSLContexts.createSystemDefault();
    private DnsResolver dnsResolver = new SystemDefaultDnsResolver();
    private TlsConfig tlsConfig = null;
    private CookieStore cookieStore = null;
    private Timeout socketTimeout;
    private Timeout connectTimeout;
    private TimeValue validateAfterInactivity;
    private TimeValue timeToLive;

    private Timeout soTimeout;
    private Boolean soReuseAddress;
    private TimeValue soLinger;
    private Boolean soKeepAlive;
    private Boolean tcpNoDelay;
    private Integer sndBufSize;
    private Integer rcvBufSize;
    private Integer backlogSize;
    private SocketAddress socksProxyAddress;

    private HttpHost proxy = null;
    private Integer maxTotal = 100;
    private Integer maxPerRoute = 10;
    private RequestConfig defaultRequestConfig = RequestConfig.DEFAULT;

    public HttpClientConfigUtils authentications(Map<String, Pair<String, String>> credentials) {
        CredentialsProviderBuilder credentialsProviderBuilder = CredentialsProviderBuilder.create();
        if (credentials != null) {
            for (Map.Entry<String, Pair<String, String>> entry : credentials.entrySet()) {
                String key = entry.getKey();
                Pair<String, String> pair = entry.getValue();
                String[] split = key.split(":");
                HttpHost httpHost = new HttpHost(split[0], split.length > 1 ? Integer.parseInt(split[1]) : 80);
                credentialsProviderBuilder.add(httpHost, pair.getKey(), pair.getValue().toCharArray());
            }
        }
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProviderBuilder.build());
        return this;
    }

    public HttpClientConfigUtils responseParserFactory(HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory) {
        this.responseParserFactory = responseParserFactory;
        return this;
    }

    public HttpClientConfigUtils requestWriterFactory(HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory) {
        this.requestWriterFactory = requestWriterFactory;
        return this;
    }

    public HttpClientConfigUtils requestWriterFactory(CharCodingConfig charCodingConfig) {
        this.charCodingConfig = charCodingConfig;
        return this;
    }

    public HttpClientConfigUtils sslcontext(SSLContext sslcontext) {
        this.sslcontext = sslcontext;
        return this;
    }

    public HttpClientConfigUtils dnsResolver(Map<String, InetAddress> resolves) {
        dnsResolver = new SystemDefaultDnsResolver() {

            @Override
            public InetAddress[] resolve(final String host) throws UnknownHostException {
                final InetAddress inetAddress = resolves.get(host);
                if (inetAddress != null) {
                    return new InetAddress[]{inetAddress};
                }
                return super.resolve(host);
            }

        };
        return this;
    }

    public HttpClientConfigUtils defaultRequestConfig(RequestConfig requestConfig) {
        this.defaultRequestConfig = defaultRequestConfig;
        return this;
    }

    public HttpClientConfigUtils cookieStore(CookieStore cookieStore) {
        this.cookieStore = cookieStore;
        return this;
    }

    public HttpClientConfigUtils connectionConfig(Timeout connectTimeout
            , Timeout socketTimeout
            , TimeValue validateAfterInactivity
            , TimeValue timeToLive) {
        this.connectTimeout = connectTimeout;
        this.socketTimeout = socketTimeout;
        this.validateAfterInactivity = validateAfterInactivity;
        this.timeToLive = timeToLive;
        return this;
    }

    public HttpClientConfigUtils socketConfig(Timeout soTimeout,
                                              boolean soReuseAddress,
                                              TimeValue soLinger,
                                              boolean soKeepAlive,
                                              boolean tcpNoDelay,
                                              int sndBufSize,
                                              int rcvBufSize,
                                              int backlogSize,
                                              SocketAddress socksProxyAddress) {
        this.soTimeout = soTimeout;
        this.soReuseAddress = soReuseAddress;
        this.soLinger = soLinger;
        this.soKeepAlive = soKeepAlive;
        this.tcpNoDelay = tcpNoDelay;
        this.sndBufSize = sndBufSize;
        this.rcvBufSize = rcvBufSize;
        this.backlogSize = backlogSize;
        this.socksProxyAddress = socksProxyAddress;
        return this;
    }

    public HttpClientConfigUtils tlsConfig(TlsConfig config) {
        this.tlsConfig = config;
        return this;
    }
    public  HttpClientConfigUtils addRequestInterceptorFirst(final HttpRequestInterceptor interceptor) {
        httpClientBuilder.addRequestInterceptorFirst(interceptor);
        return this;
    }
    public  HttpClientConfigUtils addRequestInterceptorLast(final HttpRequestInterceptor interceptor) {
        httpClientBuilder.addRequestInterceptorLast(interceptor);
        return this;
    }
    public final HttpClientConfigUtils addExecInterceptorAfter(final String existing, final String name, final ExecChainHandler interceptor) {
        httpClientBuilder.addExecInterceptorAfter(existing,name,interceptor);
        return this;
    }
    public final HttpClientConfigUtils addExecInterceptorBefore(final String existing, final String name, final ExecChainHandler interceptor) {
        httpClientBuilder.addExecInterceptorBefore(existing,name,interceptor);
        return this;
    }
    public static HttpClientConfigUtils custom() {
        return new HttpClientConfigUtils();
    }

    public CloseableHttpClient build() {
        ManagedHttpClientConnectionFactory connFactory = new ManagedHttpClientConnectionFactory(this.h1Config, charCodingConfig, requestWriterFactory, responseParserFactory);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry,
                PoolConcurrencyPolicy.STRICT,
                PoolReusePolicy.LIFO,
                TimeValue.ofMinutes(5), null, dnsResolver,
                connFactory);
        connManager.setDefaultSocketConfig(buildSocketConfig());
        connManager.setDefaultConnectionConfig(buildConnectionConfig());
        // Use TLS v1.3 only
        connManager.setDefaultTlsConfig(TlsConfig.custom()
                .setHandshakeTimeout(Timeout.ofSeconds(30))
                .setSupportedProtocols(TLS.V_1_0, TLS.V_1_1, TLS.V_1_2, TLS.V_1_3)
                .build());
        connManager.setMaxTotal(maxTotal);
        connManager.setDefaultMaxPerRoute(maxPerRoute);
        httpClientBuilder.setConnectionManager(connManager).evictExpiredConnections().evictIdleConnections(TimeValue.ofSeconds(5));
        if (cookieStore != null) {
            httpClientBuilder.setDefaultCookieStore(cookieStore);
        }
        if (proxy != null) {
            httpClientBuilder.setProxy(proxy);
        }
        if (defaultRequestConfig != null) {
            httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig);
        }

        CloseableHttpClient build = httpClientBuilder.build();
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    build.close();
                } catch (Exception e) {
                }
            }
        });
        return build;
    }

    private ConnectionConfig buildConnectionConfig() {
        ConnectionConfig.Builder connectionConfigB = ConnectionConfig.custom();
        if (this.socketTimeout != null) {
            connectionConfigB.setSocketTimeout(this.socketTimeout);
        }
        if (this.connectTimeout != null) {
            connectionConfigB.setConnectTimeout(this.connectTimeout);
        }
        if (this.validateAfterInactivity != null) {
            connectionConfigB.setValidateAfterInactivity(this.validateAfterInactivity);
        }
        if (this.timeToLive != null) {
            connectionConfigB.setTimeToLive(this.timeToLive);
        }
        ConnectionConfig connectionConfig = connectionConfigB.build();
        return connectionConfig;
    }

    private SocketConfig buildSocketConfig() {
        SocketConfig.Builder socketConfigB = SocketConfig.custom();
        if (this.soTimeout != null) {
            socketConfigB.setSoTimeout(this.soTimeout);
        }
        if (this.soReuseAddress != null) {
            socketConfigB.setSoReuseAddress(this.soReuseAddress);
        }
        if (this.soLinger != null) {
            socketConfigB.setSoLinger(this.soLinger);
        }
        if (this.soKeepAlive != null) {
            socketConfigB.setSoKeepAlive(this.soKeepAlive);
        }
        if (this.tcpNoDelay != null) {
            socketConfigB.setTcpNoDelay(this.tcpNoDelay);
        }
        if (this.sndBufSize != null) {
            socketConfigB.setSndBufSize(this.sndBufSize);
        }
        if (this.rcvBufSize != null) {
            socketConfigB.setRcvBufSize(this.rcvBufSize);
        }
        if (this.backlogSize != null) {
            socketConfigB.setBacklogSize(this.backlogSize);
        }
        if (this.socksProxyAddress != null) {
            socketConfigB.setSocksProxyAddress(this.socksProxyAddress);
        }
        SocketConfig socketConfig = socketConfigB.build();
        return socketConfig;
    }
}

工具类

package com.lg.httpclient52;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.entity.mime.StringBody;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;

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

public class HttpUtils {

    public static CloseableHttpClient httpClient = HttpClientConfigUtils.custom().build();

    public static final ObjectMapper objectMapper = new ObjectMapper();
    static {
        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);
        objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
        objectMapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
        objectMapper.configure(JsonParser.Feature.INCLUDE_SOURCE_IN_LOCATION, true);
        objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, false);
        objectMapper.configure(JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION, false);
        objectMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
        objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, true);
        objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, true);
        objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, false);
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, false);
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, false);
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, false);
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES, false);
        objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, false);
        objectMapper.configure(MapperFeature.USE_STD_BEAN_NAMING, false);
        objectMapper.configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, false);
        objectMapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
        objectMapper.configure(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS, true);
        objectMapper.configure(MapperFeature.IGNORE_MERGE_FOR_UNMERGEABLE, true);
        objectMapper.configure(MapperFeature.BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES, false);
        objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, false);
        objectMapper.configure(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS, false);
        objectMapper.configure(DeserializationFeature.USE_LONG_FOR_INTS, false);
        objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, false);
        objectMapper.configure(DeserializationFeature.WRAP_EXCEPTIONS, true);
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, false);
        objectMapper.configure(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS, false);
        objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, false);
        objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, false);
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, false);
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, false);
        objectMapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
        objectMapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, true);
        objectMapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true);
        objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
        objectMapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, true);
        objectMapper.configure(SerializationFeature.WRAP_EXCEPTIONS, true);
        objectMapper.configure(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS, true);
        objectMapper.configure(SerializationFeature.WRITE_SELF_REFERENCES_AS_NULL, false);
        objectMapper.configure(SerializationFeature.CLOSE_CLOSEABLE, false);
        objectMapper.configure(SerializationFeature.FLUSH_AFTER_WRITE_VALUE, true);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
        objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
        objectMapper.configure(SerializationFeature.WRITE_DATES_WITH_ZONE_ID, false);
        objectMapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, true);
        objectMapper.configure(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUM_KEYS_USING_INDEX, false);
        objectMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
        objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
        objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, false);
        objectMapper.configure(SerializationFeature.EAGER_SERIALIZER_FETCH, true);
        objectMapper.configure(SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID, false);
    }


    public static <T>  Response<T> httpJsonPost(String url , Map<String,String> headers,Object data,Class<T> tClass) throws Exception {

        HttpPost httppost = new HttpPost(url);
        if(headers !=null){
            for (Map.Entry<String,String> entry: headers.entrySet() ) {
                httppost.addHeader(entry.getKey(),entry.getValue());
            }
        }
        StringEntity s = new StringEntity(data instanceof String ? (String) data : objectMapper.writeValueAsString(data)
        ,ContentType.APPLICATION_JSON);
        httppost.setEntity(s);
        return sendAndreceive(tClass, httppost);
    }

    public static <T>  Response<T> httpMultipartFormPost(String url , Map<String,String> headers,Map<String,Object> param,Class<T> tClass) throws Exception {
        HttpPost httppost = new HttpPost(url);
        if(headers !=null){
            for (Map.Entry<String,String> entry: headers.entrySet() ) {
                httppost.addHeader(entry.getKey(),entry.getValue());
            }
        }
        if(param !=null){
            final MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            for (Map.Entry<String,Object> entry: param.entrySet() ) {
                 String key = entry.getKey();
                 Object value = entry.getValue();
                if(value instanceof File){
                    multipartEntityBuilder.addBinaryBody(key, (File) value);
                }else  if (value instanceof byte[]){
                    multipartEntityBuilder.addBinaryBody(key, (byte[]) value);
                }else  if (value instanceof InputStream){
                    multipartEntityBuilder.addBinaryBody(key, (InputStream) value);
                }else {
                    StringBody comment = new StringBody(value.toString(), ContentType.TEXT_XML);
                    multipartEntityBuilder.addPart(key,comment);
                }
            }
            httppost.setEntity(multipartEntityBuilder.build());
        }
        return sendAndreceive(tClass, httppost);
    }

    private static <T> Response<T> sendAndreceive(Class<T> tClass, ClassicHttpRequest request) throws IOException, ParseException {
        try ( CloseableHttpResponse response = httpClient.execute(request)){
            int code = response.getCode();
            String reasonPhrase = response.getReasonPhrase();
            Response<T> responseData = new Response<>();
            responseData.setCode(code);
            responseData.setReasonPhrase(reasonPhrase);
            if(code >= HttpStatus.SC_SUCCESS && code < HttpStatus.SC_REDIRECTION){
                String data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                if (tClass.isAssignableFrom(String.class)) {
                    responseData.setData((T) data);
                }else {
                    responseData.setData(objectMapper.readValue(data, tClass));
                }
            }
            EntityUtils.consume(response.getEntity());
            return  responseData;
        }
    }

    public static <T>  Response<T> httpPostForm(String url , Map<String,String> headers,Map<String,Object> param,Class<T> tClass) throws Exception {
        ClassicRequestBuilder build = ClassicRequestBuilder.post().setUri(new URI(url));;
        if(headers !=null){
            for (Map.Entry<String,String> entry: headers.entrySet() ) {
                build.addHeader(entry.getKey(),entry.getValue());
            }
        }
        if(param !=null){
            for (Map.Entry<String,Object> entry: param.entrySet() ) {
                build.addParameter(entry.getKey(),entry.getValue().toString());
            }
        }
        return sendAndreceive(tClass, build.build());
    }



    public static <T>  Response<T> httpGet(String url , Map<String,Object> headers,Class<T> tClass) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        if(headers !=null){
            for (Map.Entry<String,Object> entry: headers.entrySet() ) {
                httpGet.addHeader(entry.getKey(),entry.getValue());
            }
        }
        return sendAndreceive(tClass, httpGet);
    }


   static class Response<T>{
       int code;
       String reasonPhrase;
       T data;

       public int getCode() {
           return code;
       }

       public void setCode(int code) {
           this.code = code;
       }

       public String getReasonPhrase() {
           return reasonPhrase;
       }

       public void setReasonPhrase(String reasonPhrase) {
           this.reasonPhrase = reasonPhrase;
       }

       public T getData() {
           return data;
       }

       public void setData(T data) {
           this.data = data;
       }

       @Override
       public String toString() {
           return "Response{" +
                   "code=" + code +
                   ", reasonPhrase='" + reasonPhrase + '\'' +
                   ", data=" + data +
                   '}';
       }
   }

    public static void main(String[] args) throws Exception {
//        try{
//               HttpGet httpGet = new HttpGet("http://cis.vivo.xyz/cis-admin/health");
//            httpGet.addHeader("cistoken","SMZulfWkOkfdapZInhwT.yrNbHCZhuswrtwJZT9HjNcLi_Xj1sGBUL5eaA6JGNMv9cDheVHyPnY*");
//           try ( CloseableHttpResponse response = httpClient.execute(httpGet)){
//               final int code = response.getCode();
//               final String reasonPhrase = response.getReasonPhrase();
//               System.out.println(code +"\t"+ reasonPhrase);
//               final HttpEntity entity = response.getEntity();
//               System.out.println(EntityUtils.toString(entity, StandardCharsets.UTF_8));
//               EntityUtils.consume(entity);
//           }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        HashMap<String, String> headers = new HashMap<>();
        headers.put("cistoken","SMZulfWkOkfdapZInhwT.yrNbHCZhuswrtwJZT9HjNcLi_Xj1sGBUL5eaA6JGNMv9cDheVHyPnY*");

//        Response<String> objectResponse = httpGet("http://cis.vivo.xyz/cis-admin/health", map, String.class);
//        System.out.println(objectResponse)
//        httpClient =  HttpClientConfigUtils.custom()  .addRequestInterceptorFirst(new HttpRequestInterceptor() {
//            @Override
//            public void process(HttpRequest request,EntityDetails entity,HttpContext context) throws HttpException, IOException {
//                request.setHeader("request-id", UUID.randomUUID());
//            }
//        }) .addExecInterceptorAfter(ChainElement.PROTOCOL.name(), "custom", (request, scope, chain) -> {
//                    System.out.println("addExecInterceptorAfter");
//                        return chain.proceed(request, scope);
//                })
//                .build();
//        Response<String> objectResponse = httpPostForm("http://127.0.0.1:9998/web/add", headers,param, String.class);
//        System.out.println(objectResponse);
//        HashMap<String, Object> param = new HashMap<>();
//        param.put("cistoken","SMZulfWkOkfdapZInhwT.yrNbHCZhuswrtwJZT9HjNcLi_Xj1sGBUL5eaA6JGNMv9cDheVHyPnY*");
//        param.put("cistoken1",1);
//        param.put("cistoken2",new Date());
//        param.put("cistoken3",new File("E:\\workspace\\httpcomponents-client-rel-v5.2-alpha1\\httpclient5\\src\\main\\java\\org\\apache\\hc\\client5\\http\\entity\\mime\\MultipartEntityBuilder.java"));
//        param.put("cistoken4","E:\\workspace\\httpcomponents-client-rel-v5.2-awod中文lient5\\http\\entity\\mime\\MultipartEntityBuilder.java".getBytes(StandardCharsets.UTF_8));
//        param.put("cistoken5",new FileInputStream("E:\\workspace\\httpcomponents-client-rel-v5.2-alpha1\\httpclient5\\src\\main\\java\\org\\apache\\hc\\client5\\http\\entity\\mime\\MultipartEntityBuilder.java"));
//        Response<String> objectResponse = httpMultipartFormPost("http://127.0.0.1:9998/web/uploadsinglefile", headers,param, String.class);
//        System.out.println(objectResponse);
        TarFileInfo tarFileInfo = new TarFileInfo();
        tarFileInfo.setFilename("hello world");
        tarFileInfo.setPath("ddddd");
        Response<String> stringResponse = httpJsonPost("http://127.0.0.1:9998/web/downzipbyZipArchive", headers, tarFileInfo, String.class);
        System.out.println(stringResponse);
    }
}

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-04-22 19:15:05  更:2022-04-22 19:18:18 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/30 4:29:51-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码