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

  • 问题背景
    • HttpClient工具类调用url实例,附源码(一)
    • HttpClient内外访问外网,添加代理(二)
  • 项目搭建
  • Lyric: 你已走得很远

问题背景

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

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

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 {// 创建httpPostHttpPost 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 {// 创建httpPostHttpPost 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();}}}@Overridepublic 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: 你已走得很远

HttpClient内外访问外网,添加代理(二)相关推荐

  1. 《Linux运维总结:内网服务器通过代理访问外网服务器(方法二)》

    一.背景 说明:192.168.1.191可以上外网,192.168.1.192不能上外网,需要使用代理的方法实现192.168.1.192主机可以访问外网. 内网ip 外网ip 操作系统 192.1 ...

  2. nginx正向代理配置,解决内外网隔离无法访问外网web地址问题

    前提: 内网电脑只能能够访问外网电脑的8086端口. 外网电脑能否访问外网地址. nginx.conf配置文件示例如下: worker_processes  1; events {     worke ...

  3. 《Linux运维总结:内网服务器通过代理访问外网服务器(方法一)》

    一.背景 说明:192.168.1.191可以上外网,192.168.1.192不能上外网,需要使用代理的方法实现192.168.1.192主机可以访问外网. 内网ip 外网ip 操作系统 192.1 ...

  4. Linux服务器上设置全局代理访问外网并验证

    Linux服务器上设置全局代理访问外网并验证 昨天碰到了内网需要访问外网下载的情况,需要在服务器上设置代理,没别的,就记录一下自己跳过的坑. 1.前提是已经搭建好了一台代理服务器 2.Linux设置全 ...

  5. 使用nginx代理访问外网

    假设SERVER A: 192.168.10.10能访问外网,DNS IP是62.138.228.28(查看DNS IP:  cat /etc/resolv.conf ) 1.在SERVER A安装N ...

  6. linux内网机器访问外网代理设置

     摘要: 公司一般出于安全考虑, 在同一局域网中只有一台机器可以访问外网,运维进行了整体的限制, 但是在后面的工作中,需要在机器上安装一些软件,及命令,所以其他的机器需要访问外网来简化工作, 但又 ...

  7. 使用squid 解决内网服务器通过设置代理访问外网

    背景 线上算法服务有一个偶尔触发的逻辑需要访问三方的api,由于生产服务器无法访问外网,因此一直使用代理进行外网访问,最近代理服务器被重装了,由于该代理是前同事装的,导致这台服务器重装时候没有通知相应 ...

  8. linux 内网机器访问外网代理设置

    摘要: 公司一般出于安全考虑, 在同一局域网中只有一台机器可以访问外网,运维进行了整体的限制, 但是在后面的工作中,需要在机器上安装一些软件,及命令,所以其他的机器需要访问外网来简化工作, 但又不能打 ...

  9. java-配置代理访问外网谷歌苹果外网

    java配置代理访问外网api 1.打开代理软件查看代理软件端口号 2.idea添加代理 配置完点击最后箭头测试 eg: https://www.google.com/ 3.启动类添加代理配置 Str ...

最新文章

  1. cmake 注意事项
  2. linux 软件安装基本操作
  3. linux 下C调用Python 模块
  4. call_user_func
  5. 山东管理学院计算机专业在哪个校区,2019年山东管理学院新生在哪个校区及新生开学报到时间...
  6. java 监听文件内容_java 监听文件内容变化
  7. opencv颜色识别_opencv-python污水颜色识别
  8. android.net.wifi的简单使用方法
  9. 什么是Spring EL表达式
  10. java json删除指定元素_简洁而优雅,Python Tablib实现将数据导出为Excel, Json等N种格式...
  11. tkinter 隐藏_python Tkinter()如何隐藏UI
  12. Bailian2871 Bailian3682 整数奇偶排序【排序】
  13. [转载] python并行处理任务_Python 并行任务技巧
  14. 简单网页布局的html代码网站,一个简单的网页布局代码
  15. Java项目:在线购书商城系统(java+jsp+mysql+servlert+ajax)
  16. linux 内核头文件、内核库文件
  17. Linux中vim命令详解
  18. 通过 purge_relay_logs 自动清理relaylog
  19. 美国篮球巨星科比坠机去世 年仅41岁
  20. 前端实现csv文件类型下载

热门文章

  1. c语言sprintf函数 long,基于C语言sprintf函数的深入理解
  2. Spring自动装配实现原理
  3. [Metricbeat] Metricbeat监控golang服务器
  4. T细胞/B细胞表位预测
  5. 软件工程SSM毕设旅游信息发布管理系统(含源码+论文)
  6. SpringDataElasticsearch解决5,000 milliseconds timeout on connection http-outgoing-8237946 [ACTIVE]
  7. 乔伊斯。文森特_熊猫和文森特简介
  8. mysql 判断当前星期_mysql 获取当前日期周一和周日
  9. 单片机c语言孔雀开屏,单片机C语言案例程教学指南.doc
  10. 基于javaweb在线投票管理系统ssm