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认证,所以这里记录一下,希望对你有用。

相关推荐
心之伊始15 分钟前
深入理解 AbstractQueuedSynchronizer(AQS):构建高性能同步器的基石
java·开发语言
静渊谋35 分钟前
攻防世界-Check
java·安全·网络安全
代码充电宝1 小时前
LeetCode 算法题【简单】49. 字母异位词分组
java·算法·leetcode·面试·哈希算法
摸鱼的老谭2 小时前
Java学习之旅第一季-28:Java基础语法测试题
java·java基础测试
Brookty2 小时前
深入解析Java类加载与实例化流程
java·开发语言·学习
YSRM2 小时前
Leetcode+Java+图论+岛屿问题
java·算法·leetcode·图论
codecrafter1233 小时前
MATLAB中的while循环:从入门到精通的完整指南
java·数据库·其他·matlab
Zz_waiting.4 小时前
Spring AOP
java·spring·代理模式·springaop
没有bug.的程序员4 小时前
MySQL 安全与权限管理:从基础到生产级安全实践
java·mysql·安全·adb·权限
_extraordinary_4 小时前
Java JVM --- JVM内存区域划分,类加载,GC垃圾回收
java·开发语言·jvm