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 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> HttpClient内外访问外网,添加代理(二) -> 正文阅读

[网络协议]HttpClient内外访问外网,添加代理(二)

问题背景

有时候不是任何网络都可以访问自己的程序,自己也不能随意访问外网,做安全隔离,但有时确实需要与外面交互,这个时候就需要使用外网代理了
注意事项:

  • 代码可以复用上一篇文章,添加一点小改动就行了

HttpClient工具类调用url实例,附源码(一)

HttpClient内外访问外网,添加代理(二)

项目搭建

1 在httpclient工具类中添加代理

/*
 * Copyright 2019 The FATE Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yg.thirdtest.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@Service
@Slf4j
public class HttpClientPoolUtil implements InitializingBean {
    private PoolingHttpClientConnectionManager poolConnManager;
    private RequestConfig requestConfig;
    private CloseableHttpClient httpClient;

    private static void config(HttpRequestBase httpRequestBase) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(20000)
                .setConnectTimeout(20000)
                .setSocketTimeout(20000).build();
        httpRequestBase.addHeader("Content-Type", "application/json;charset=UTF-8");
        httpRequestBase.setConfig(requestConfig);
    }

    private void initPool() {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                    "http", PlainConnectionSocketFactory.getSocketFactory()).register(
                    "https", sslsf).build();
            poolConnManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            poolConnManager.setMaxTotal(500);
            poolConnManager.setDefaultMaxPerRoute(500);

            int socketTimeout = 1200000;
            int connectTimeout = 100000;
            int connectionRequestTimeout = 100000;
            HttpHost proxy = new HttpHost("172.16.12.144", 1118);
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                    connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                    connectTimeout).setProxy(proxy).build();
//            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
//                    connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
//                    connectTimeout).build();
            httpClient = getConnection();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            e.printStackTrace();
        }
    }

    private CloseableHttpClient getConnection() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(poolConnManager)
                .setDefaultRequestConfig(requestConfig)

                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, false))
                .build();
        return httpClient;
    }

    public JSONObject postForJsonObject(String url, String jsonStr) {
        log.debug("url = " + url + " ,  json = " + jsonStr);
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        try {

            // 创建httpPost
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");

            StringEntity entity = new StringEntity(jsonStr, "UTF-8");
            entity.setContentType("application/json");
            entity.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(entity);
            //发送post请求
            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
                log.debug("request success cost = {}, result = {}", System.currentTimeMillis() - start, result);
                return result;
            } else {
                log.error("bad response: {}", JSONObject.parseObject(EntityUtils.toString(response.getEntity())));
            }
        } catch (Exception e) {
            log.error("=============[\"异常\"]======================, e: {}", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public String post(String url, Map<String, Object> requestData) {
        HttpPost httpPost = new HttpPost(url);
        config(httpPost);
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(requestData), "UTF-8");
        stringEntity.setContentEncoding(StandardCharsets.UTF_8.toString());
        httpPost.setEntity(stringEntity);
        return getResponse(httpPost);
    }


    public JSONArray post(String url, String jsonStr) {
        log.debug("url = " + url + " ,  json = " + jsonStr);
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        JSONArray result = new JSONArray();
        try {
            // 创建httpPost
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");

            StringEntity entity = new StringEntity(jsonStr, StandardCharsets.UTF_8.toString());
            entity.setContentType("application/json");
            entity.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(entity);
            //发送post请求
            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = JSONObject.parseArray(EntityUtils.toString(response.getEntity()));
                log.debug("request success cost = {}, result = {}", System.currentTimeMillis() - start, result);
                return result;
            } else {
                log.error("bad response, result: {}", EntityUtils.toString(response.getEntity()));
            }
        } catch (Exception e) {
            log.error("=============[\"异常\"]======================, e: {}", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public String get(String url) {
        HttpGet httpGet = new HttpGet(url);
        config(httpGet);
        return getResponse(httpGet);
    }

    private String getResponse(HttpRequestBase request) {
        CloseableHttpResponse response = null;
        try {

            response = httpClient.execute(request,
                    HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, StandardCharsets.UTF_8.toString());
            EntityUtils.consume(entity);

            return result;
        } catch (IOException e) {
            log.error("send http error", e);
            return "";
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initPool();
    }
}

主要就是这几行进行更改

            HttpHost proxy = new HttpHost("172.16.12.144", 1118);
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                    connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                    connectTimeout).setProxy(proxy).build();




作为程序员第 97 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …

Lyric: 你已走得很远

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-04-06 16:25:55  更:2022-04-06 16:27:24 
 
开发: 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年11日历 -2024/11/26 4:40:19-

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