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

相关推荐
堕落年代11 分钟前
HTTP请求当中若用户还没接收到返回数据就离线但服务器资源已经删除的情况
网络·网络协议·http
风象南17 分钟前
SpringBoot中3种条件装配技术
java·spring boot·后端
Java小白中的菜鸟19 分钟前
深入理解Java反射
java·开发语言
自由与自然21 分钟前
乐观锁与悲观锁的使用场景
java·服务器·数据库
爱的叹息3 小时前
spring mvc 中 RestTemplate 全面详解及示例
java·spring·mvc
.生产的驴7 小时前
SpringBoot 接口限流Lua脚本接合Redis 服务熔断 自定义注解 接口保护
java·大数据·数据库·spring boot·redis·后端·lua
洛可可白8 小时前
Spring Boot中自定义注解的创建与使用
java·spring boot·后端
Alkaid:9 小时前
解决Long类型前端精度丢失和正常传回后端问题
java·前端·javascript·vue.js
唐人街都是苦瓜脸9 小时前
Java RPC 框架是什么
java·开发语言·rpc
魔道不误砍柴功9 小时前
Java性能调优2025:从JVM到Kubernetes的全链路优化策略
java·jvm·kubernetes