java使用smiley-http-proxy-servlet实现反向代理,跳过SSL认证

前言

nginx可以实现反向代理,但是有时候需要使用java代码来实现,经过摸索,发现有开源的项目可以实现,所以简单记录一下如何使用

一、引入依赖

没啥好说

XML 复制代码
    <dependency>
      <groupId>org.mitre.dsmiley.httpproxy</groupId>
      <artifactId>smiley-http-proxy-servlet</artifactId>
      <version>1.12.1</version>
    </dependency>

二、重写Servlet

该项目的核心类是ProxyServlet,主要操作都在这个类中实现了,我们可以继承该类,重写其中的方法,自定义实现一些功能。

这里我们继承ProxyServlet,重写了createHttpClient方法,使其跳过ssl认证

java 复制代码
@Slf4j
public class CustomProxyServlet extends ProxyServlet {

    /**
     * 重写HttpClient,跳过ssl认证
     *
     * @return {@link HttpClient}
     */
    @Override
    protected HttpClient createHttpClient() {
        HttpClientBuilder clientBuilder = getHttpClientBuilder()
                .setDefaultRequestConfig(buildRequestConfig())
                .setDefaultSocketConfig(buildSocketConfig());

        clientBuilder.setMaxConnTotal(maxConnections);
        clientBuilder.setMaxConnPerRoute(maxConnections);
        if(! doHandleCompression) {
            clientBuilder.disableContentCompression();
        }
        if (useSystemProperties){
            clientBuilder.useSystemProperties();
        }

        SSLContext sslContext = this.getSslContext();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        clientBuilder.setSSLSocketFactory(sslSocketFactory);
        return super.buildHttpClient(clientBuilder);
    }

    /**
     * 获取sslContext
     * @return {@link SSLContext}
     */
    public SSLContext getSslContext() {
        SSLContext sslContext = null;
        try {
            sslContext = SSLContextBuilder.create()
                    .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                    .build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
            log.error("获取sslContext失败", e);
        }
        return sslContext;
    }

}

三、添加配置

添加配置类配置一下代理信息

代理信息配置

java 复制代码
@Data
public class ProxyProperties {

    /**
     * 映射
     */
    private String mapping;

    /**
     * 目标url
     */
    private String targetUrl;
    
}

添加配置,控制是否启代理

java 复制代码
@Data
@ConfigurationProperties(prefix = "proxy")
public class ProxyConfig {
    
    /**
     * 启用日志
     */
    private boolean enableLog;

    /**
     * 配置
     */
    private List<ProxyProperties> configs;
    
}

自动装配,获取自定义配置信息,通过for循环配置多个servlet

java 复制代码
import lombok.RequiredArgsConstructor;
import org.mitre.dsmiley.httpproxy.ProxyServlet;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import java.util.List;

@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties(ProxyConfig.class)
public class ProxyAutoConfiguration implements ServletContextInitializer {
    
    private final ProxyConfig proxyConfig;
    
    /**
     * Configure the given {@link ServletContext} with any servlets, filters, listeners
     * context-params and attributes necessary for initialization.
     *
     * @param servletContext the {@code ServletContext} to initialize
     */
    @Override
    public void onStartup(ServletContext servletContext) {
        List<ProxyProperties> configs = proxyConfig.getConfigs();
        for (int i = 0; i < configs.size(); i++) {
            ProxyProperties properties = configs.get(i);
            //定义多个servlet
            ServletRegistration initServlet = servletContext.addServlet("ProxyServlet"+i, CustomProxyServlet.class);
            initServlet.addMapping(properties.getMapping());
            initServlet.setInitParameter(ProxyServlet.P_TARGET_URI, properties.getTargetUrl());
            initServlet.setInitParameter(ProxyServlet.P_FORWARDEDFOR, "false");
            initServlet.setInitParameter(ProxyServlet.P_LOG, Boolean.toString(proxyConfig.isEnableLog()));
        }
    }
}

写在后面的话

百度使用方法,大部分只能代理一个地址,而且不支持跳过ssl认证,所以这里记录一下,希望对你有用。

相关推荐
栈与堆10 小时前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
OC溥哥99911 小时前
Paper MinecraftV3.0重大更新(下界更新)我的世界C++2D版本隆重推出,拷贝即玩!
java·c++·算法
星火开发设计11 小时前
C++ map 全面解析与实战指南
java·数据结构·c++·学习·算法·map·知识
*才华有限公司*11 小时前
RTSP视频流播放系统
java·git·websocket·网络协议·信息与通信
gelald11 小时前
ReentrantLock 学习笔记
java·后端
计算机学姐11 小时前
基于SpringBoot的校园资源共享系统【个性化推荐算法+数据可视化统计】
java·vue.js·spring boot·后端·mysql·spring·信息可视化
一条咸鱼_SaltyFish11 小时前
[Day15] 若依框架二次开发改造记录:定制化之旅 contract-security-ruoyi
java·大数据·经验分享·分布式·微服务·架构·ai编程
跟着珅聪学java11 小时前
JavaScript 底层原理
java·开发语言
Mr. Cao code11 小时前
Docker数据管理:持久化存储最佳实践
java·docker·容器
强子感冒了11 小时前
Java 学习笔记:File类核心API详解与使用指南
java·笔记·学习