zoukankan      html  css  js  c++  java
  • springboot实现*,动态代理目标地址

    网上找了很多文章,各种照搬,只能自己实现

    基于开源项目HTTP-Proxy-Servlet实现

    开源项目地址:https://github.com/mitre/HTTP-Proxy-Servlet

    1. 添加依赖

    <dependency>
        <groupId>org.mitre.dsmiley.httpproxy</groupId>
        <artifactId>smiley-http-proxy-servlet</artifactId>
        <version>1.11</version>
    </dependency>

    2. 实现自己的ProxyServlet,重写service方法,官方通过配置servlet参数只能代理一个目标地址,通过自己拓展service方法,进行逻辑判断可以动态代理到不同的目标地址,参考代码如下:

        @Override
        protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException {
    
            String targetUri = "http://www.baidu.com/";
    
            servletRequest.setAttribute(ATTR_TARGET_URI, null);
            super.targetUri = targetUri;
    
            URI uri = null;
            try {
                uri = new URI(targetUri);
            } catch (URISyntaxException e) {
                log.error("创建URI对象出错, targetUri[{}]", targetUri, e);
            }
            servletRequest.setAttribute(ATTR_TARGET_HOST, null);
            super.targetHost = URIUtils.extractHost(uri);
    
            super.service(servletRequest, servletResponse);
    
        }

    3. springboot中注册servlet,参考代码如下:

    @Configuration
    public class ProxyServletConfiguration {
    
        @Bean
        public ServletRegistrationBean<DiskProxyServlet> servletServletRegistrationBean() {
            ServletRegistrationBean<DiskProxyServlet> servletRegistrationBean = new ServletRegistrationBean<>(new DiskProxyServlet(), "/toProxy");
            servletRegistrationBean.addInitParameter(ProxyServlet.P_LOG, "true");
            return servletRegistrationBean;
        }
    
    }

    4. 浏览器访问http://ip:port/toProxy,会代理到百度首页;

  • 相关阅读:
    PHP之十六个魔术方法详解
    PHP之十六个魔术方法详解
    让Docker容器使用静态独立的外部IP(便于集群组建)
    桥接和nat模式区别
    使用 GitHub / GitLab 的 Webhooks 进行网站自动化部署
    docker gitlab
    docker gitlab安装
    docker ui管理工具
    docker 批量删除容器
    Scrapy设置代理
  • 原文地址:https://www.cnblogs.com/changxy-codest/p/13093132.html
Copyright © 2011-2022 走看看