httpclient支持socks5和http代理调用接口

2024-09-04 06:04

本文主要是介绍httpclient支持socks5和http代理调用接口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

httpclient支持socks5和http代理调用接口

package com.ruoyi.web.controller.util;import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.DnsResolver;
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.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.poi.util.IOUtils;import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;/*** 支持socks5和http代理*/
public class HttpUtil {public static void main(String[] args) {String url = "http://ip-api.com/json/?lang=zh-CN";String http = "http://127.0.0.1:10163:admin:password";String socks = "socks5://127.0.0.1:20001:admin:password";ProxyVO socksVo = ProxyVO.resolver(socks);System.out.println(doGet(socksVo, url, null, null));ProxyVO httpVo = ProxyVO.resolver(http);System.out.println(doGet(httpVo, url, null, null));}public static String doGet(ProxyVO proxyVo, String url, Map<String, String> headers, Map<String, String> param) {try {URIBuilder builder = new URIBuilder(url);// 设置参数 builder.addParameter(key, param.get(key));Optional.ofNullable(param).ifPresent(h -> h.forEach(builder::addParameter));HttpGet httpget = new HttpGet(builder.build());// 设置header setHeader(key, headers.get(key));Optional.ofNullable(headers).ifPresent(h -> h.forEach(httpget::setHeader));if (proxyVo.isSocks5()) {return doExecuteSocks5(proxyVo, httpget);} else {return doExecuteHttp(proxyVo, httpget,url);}} catch (Exception e) {e.printStackTrace();}return null;}public static String doPost(ProxyVO proxyVo, String url, Map<String, String> headers, Map<String, String> param) {// 创建Http Post请求HttpPost httpPost = new HttpPost(url);// 设置headerOptional.ofNullable(headers).ifPresent(h -> h.forEach(httpPost::setHeader));// 创建参数列表if (param != null) {List<NameValuePair> paramList = param.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())).collect(Collectors.toList());// 模拟表单httpPost.setEntity(new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8));}// 执行http请求if (proxyVo.isSocks5()) {return doExecuteSocks5(proxyVo, httpPost);} else {return doExecuteHttp(proxyVo, httpPost,url);}}/*** Socks5 代理*/public static String doExecuteSocks5(ProxyVO proxyVo, HttpUriRequest httpRequest) {CloseableHttpClient httpclient = null;CloseableHttpResponse response = null;try {//用户名和密码验证Authenticator.setDefault(new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(proxyVo.getUserName(), proxyVo.getPwd().toCharArray());}});httpclient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create().register("http", new MyConnectionSocketFactory()).register("https", new MySSLConnectionSocketFactory(SSLContexts.createSystemDefault())).build(),new FakeDnsResolver())).build();HttpClientContext context = HttpClientContext.create();context.setAttribute("socks.address", new InetSocketAddress(proxyVo.getHost(), proxyVo.getPort()));response = httpclient.execute(httpRequest, context);if (response.getStatusLine().getStatusCode() == 200) {
//                return new String(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);}} catch (Exception e) {e.printStackTrace();} finally {IOUtils.closeQuietly(response);IOUtils.closeQuietly(httpclient);}return null;}/*** http 代理*/public static String doExecuteHttp(ProxyVO proxyVo, HttpRequestBase httpRequest,String url) {try {// 设置代理HttpHostHttpHost proxy = new HttpHost(proxyVo.getHost(), proxyVo.getPort(), Proxy.Type.HTTP.name());URI uri = new URI(url);// 设置要访问的HttpHost,即是目标站点的HttpHostHttpHost httpTarget = new HttpHost(uri.getHost(), uri.getPort());// 设置认证CredentialsProvider provider = new BasicCredentialsProvider();provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(proxyVo.getUserName(), proxyVo.getPwd()));CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();RequestConfig config = RequestConfig.custom().setProxy(proxy).build();httpRequest.setConfig(config);CloseableHttpResponse response = httpClient.execute(httpTarget, httpRequest);if (response.getStatusLine().getStatusCode() == 200) {return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);}} catch (IOException | URISyntaxException e) {e.printStackTrace();}return null;}static class FakeDnsResolver implements DnsResolver {@Overridepublic InetAddress[] resolve(String host) throws UnknownHostException {return new InetAddress[]{InetAddress.getByAddress(new byte[]{1, 1, 1, 1})};}}static class MyConnectionSocketFactory extends PlainConnectionSocketFactory {@Overridepublic Socket createSocket(final HttpContext context) {return new Socket(new Proxy(Proxy.Type.SOCKS, (InetSocketAddress) context.getAttribute("socks.address")));}@Overridepublic Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException {return super.connectSocket(connectTimeout, socket, host, InetSocketAddress.createUnresolved(host.getHostName(), remoteAddress.getPort()), localAddress, context);}}static class MySSLConnectionSocketFactory extends SSLConnectionSocketFactory {public MySSLConnectionSocketFactory(final SSLContext sslContext) {super(sslContext, ALLOW_ALL_HOSTNAME_VERIFIER);}@Overridepublic Socket createSocket(final HttpContext context) {return new Socket(new Proxy(Proxy.Type.SOCKS, (InetSocketAddress) context.getAttribute("socks.address")));}@Overridepublic Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress,InetSocketAddress localAddress, HttpContext context) throws IOException {return super.connectSocket(connectTimeout, socket, host, InetSocketAddress.createUnresolved(host.getHostName(),remoteAddress.getPort()), localAddress, context);}}
}
package com.ruoyi.web.controller.util;import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.stream.Stream;@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ProxyVO {// 代理信息private boolean isSocks5;private String host;private int port;private String userName;private String pwd;public static ProxyVO resolver(String proxyUrl) {if (StrUtil.isEmpty(proxyUrl)) return null;String prefix = Stream.of("socks5://", "http://").filter(proxyUrl::startsWith).findFirst().orElse(null);if (prefix == null) return null;String[] split = StrUtil.replace(proxyUrl, prefix, "").split(":");if (split.length != 4) return null;return ProxyVO.builder().isSocks5(StrUtil.startWith(proxyUrl, "socks5://")).host(split[0]).port(Integer.parseInt(split[1])).userName(split[2]).pwd(split[3]).build();}
}

这篇关于httpclient支持socks5和http代理调用接口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1135201

相关文章

SpringKafka消息发布之KafkaTemplate与事务支持功能

《SpringKafka消息发布之KafkaTemplate与事务支持功能》通过本文介绍的基本用法、序列化选项、事务支持、错误处理和性能优化技术,开发者可以构建高效可靠的Kafka消息发布系统,事务支... 目录引言一、KafkaTemplate基础二、消息序列化三、事务支持机制四、错误处理与重试五、性能优

go中空接口的具体使用

《go中空接口的具体使用》空接口是一种特殊的接口类型,它不包含任何方法,本文主要介绍了go中空接口的具体使用,具有一定的参考价值,感兴趣的可以了解一下... 目录接口-空接口1. 什么是空接口?2. 如何使用空接口?第一,第二,第三,3. 空接口几个要注意的坑坑1:坑2:坑3:接口-空接口1. 什么是空接

在C#中调用Python代码的两种实现方式

《在C#中调用Python代码的两种实现方式》:本文主要介绍在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#调用python代码的方式1. 使用 Python.NET2. 使用外部进程调用 Python 脚本总结C#调

SpringCloud之LoadBalancer负载均衡服务调用过程

《SpringCloud之LoadBalancer负载均衡服务调用过程》:本文主要介绍SpringCloud之LoadBalancer负载均衡服务调用过程,具有很好的参考价值,希望对大家有所帮助,... 目录前言一、LoadBalancer是什么?二、使用步骤1、启动consul2、客户端加入依赖3、以服务

Vue 调用摄像头扫描条码功能实现代码

《Vue调用摄像头扫描条码功能实现代码》本文介绍了如何使用Vue.js和jsQR库来实现调用摄像头并扫描条码的功能,通过安装依赖、获取摄像头视频流、解析条码等步骤,实现了从开始扫描到停止扫描的完整流... 目录实现步骤:代码实现1. 安装依赖2. vue 页面代码功能说明注意事项以下是一个基于 Vue.js

Go语言中最便捷的http请求包resty的使用详解

《Go语言中最便捷的http请求包resty的使用详解》go语言虽然自身就有net/http包,但是说实话用起来没那么好用,resty包是go语言中一个非常受欢迎的http请求处理包,下面我们一起来学... 目录安装一、一个简单的get二、带查询参数三、设置请求头、body四、设置表单数据五、处理响应六、超

如何用java对接微信小程序下单后的发货接口

《如何用java对接微信小程序下单后的发货接口》:本文主要介绍在微信小程序后台实现发货通知的步骤,包括获取Access_token、使用RestTemplate调用发货接口、处理AccessTok... 目录配置参数 调用代码获取Access_token调用发货的接口类注意点总结配置参数 首先需要获取Ac

讯飞webapi语音识别接口调用示例代码(python)

《讯飞webapi语音识别接口调用示例代码(python)》:本文主要介绍如何使用Python3调用讯飞WebAPI语音识别接口,重点解决了在处理语音识别结果时判断是否为最后一帧的问题,通过运行代... 目录前言一、环境二、引入库三、代码实例四、运行结果五、总结前言基于python3 讯飞webAPI语音

MyBatis-Plus中Service接口的lambdaUpdate用法及实例分析

《MyBatis-Plus中Service接口的lambdaUpdate用法及实例分析》本文将详细讲解MyBatis-Plus中的lambdaUpdate用法,并提供丰富的案例来帮助读者更好地理解和应... 目录深入探索MyBATis-Plus中Service接口的lambdaUpdate用法及示例案例背景

一文教你解决Python不支持中文路径的问题

《一文教你解决Python不支持中文路径的问题》Python是一种广泛使用的高级编程语言,然而在处理包含中文字符的文件路径时,Python有时会表现出一些不友好的行为,下面小编就来为大家介绍一下具体的... 目录问题背景解决方案1. 设置正确的文件编码2. 使用pathlib模块3. 转换路径为Unicod