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

相关文章

高效+灵活,万博智云全球发布AWS无代理跨云容灾方案!

摘要 近日,万博智云推出了基于AWS的无代理跨云容灾解决方案,并与拉丁美洲,中东,亚洲的合作伙伴面向全球开展了联合发布。这一方案以AWS应用环境为基础,将HyperBDR平台的高效、灵活和成本效益优势与无代理功能相结合,为全球企业带来实现了更便捷、经济的数据保护。 一、全球联合发布 9月2日,万博智云CEO Michael Wong在线上平台发布AWS无代理跨云容灾解决方案的阐述视频,介绍了

如何在页面调用utility bar并传递参数至lwc组件

1.在app的utility item中添加lwc组件: 2.调用utility bar api的方式有两种: 方法一,通过lwc调用: import {LightningElement,api ,wire } from 'lwc';import { publish, MessageContext } from 'lightning/messageService';import Ca

在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern) 确保一个类只有一个实例,并提供一个全局访问点。 示例代码: class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;this.data = [];}addData(value)

BUUCTF靶场[web][极客大挑战 2019]Http、[HCTF 2018]admin

目录   [web][极客大挑战 2019]Http 考点:Referer协议、UA协议、X-Forwarded-For协议 [web][HCTF 2018]admin 考点:弱密码字典爆破 四种方法:   [web][极客大挑战 2019]Http 考点:Referer协议、UA协议、X-Forwarded-For协议 访问环境 老规矩,我们先查看源代码

【Linux】应用层http协议

一、HTTP协议 1.1 简要介绍一下HTTP        我们在网络的应用层中可以自己定义协议,但是,已经有大佬定义了一些现成的,非常好用的应用层协议,供我们直接使用,HTTP(超文本传输协议)就是其中之一。        在互联网世界中,HTTP(超文本传输协议)是一个至关重要的协议,他定义了客户端(如浏览器)与服务器之间如何进行通信,以交换或者传输超文本(比如HTML文档)。

Java 后端接口入参 - 联合前端VUE 使用AES完成入参出参加密解密

加密效果: 解密后的数据就是正常数据: 后端:使用的是spring-cloud框架,在gateway模块进行操作 <dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>30.0-jre</version></dependency> 编写一个AES加密

如何确定 Go 语言中 HTTP 连接池的最佳参数?

确定 Go 语言中 HTTP 连接池的最佳参数可以通过以下几种方式: 一、分析应用场景和需求 并发请求量: 确定应用程序在特定时间段内可能同时发起的 HTTP 请求数量。如果并发请求量很高,需要设置较大的连接池参数以满足需求。例如,对于一个高并发的 Web 服务,可能同时有数百个请求在处理,此时需要较大的连接池大小。可以通过压力测试工具模拟高并发场景,观察系统在不同并发请求下的性能表现,从而

【LabVIEW学习篇 - 21】:DLL与API的调用

文章目录 DLL与API调用DLLAPIDLL的调用 DLL与API调用 LabVIEW虽然已经足够强大,但不同的语言在不同领域都有着自己的优势,为了强强联合,LabVIEW提供了强大的外部程序接口能力,包括DLL、CIN(C语言接口)、ActiveX、.NET、MATLAB等等。通过DLL可以使用户很方便地调用C、C++、C#、VB等编程语言写的程序以及windows自带的大

Anaconda 中遇到CondaHTTPError: HTTP 404 NOT FOUND for url的问题及解决办法

最近在跑一个开源项目遇到了以下问题,查了很多资料都大(抄)同(来)小(抄)异(去)的,解决不了根本问题,费了很大的劲终于得以解决,记录如下: 1、问题及过程: (myenv) D:\Workspace\python\XXXXX>conda install python=3.6.13 Solving environment: done.....Proceed ([y]/n)? yDownloa

java线程深度解析(一)——java new 接口?匿名内部类给你答案

http://blog.csdn.net/daybreak1209/article/details/51305477 一、内部类 1、内部类初识 一般,一个类里主要包含类的方法和属性,但在Java中还提出在类中继续定义类(内部类)的概念。 内部类的定义:类的内部定义类 先来看一个实例 [html]  view plain copy pu