基于springboot使用apache httpClient实现简单的http/https请求代理

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
    </parent>

    <groupId>com.yxs.proxy</groupId>
    <artifactId>proxy-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <spring-boot.version>2.2.2.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-undertow</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <fork>true</fork>
                    <addResources>true</addResources>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
package com.yxs.proxy.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * http 代理层
 *
 * @author yxs
 */
@Slf4j
@RestController
@RequestMapping("/proxy")
public class ProxyHttpReqController {

    @Value("${forwardTargetAddress}")
    private String forwardTargetAddress;

    @Value("${reverseTargetAddress}")
    private String reverseTargetAddress;

    /**
     * http 正向代理
     */
    @RequestMapping("/forward/**")
    public void forward(HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        URI uri = new URI(request.getRequestURI());
        String path = uri.getPath();
        String target = (StringUtils.isEmpty(request.getHeader("forwardTargetAddress")) ? forwardTargetAddress : request.getHeader("forwardTargetAddress"))
                + path.replace("/proxy/forward", "");
        router(request, response, target);
    }

    /**
     * http 反向代理
     */
    @RequestMapping("/reverse/**")
    public void reverse(HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        URI uri = new URI(request.getRequestURI());
        String path = uri.getPath();
        String target = reverseTargetAddress + path.replace("/proxy/reverse", "");
        router(request, response, target);
    }

    private static void router(HttpServletRequest request, HttpServletResponse response, String target) throws URISyntaxException, IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        String query = request.getQueryString();
        if (query != null && !query.isEmpty() && !"null".equals(query)) {
            target = target + "?" + query;
        }
        URI newUri = new URI(target);
        // 执行代理查询
        String methodName = request.getMethod();
        HttpMethod httpMethod = HttpMethod.resolve(methodName);
        if (httpMethod == null) {
            return;
        }
        // 创建一个信任所有证书的SSLContext
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();

        // 创建一个NoopHostnameVerifier(不验证主机名)
        NoopHostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

        // 创建一个SSLConnectionSocketFactory,使用我们的SSLContext和HostnameVerifier
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

        // 创建一个CloseableHttpClient,使用我们的SSLSocketFactory
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();

        // 创建一个HttpComponentsClientHttpRequestFactory,使用我们的HttpClient
        ClientHttpRequest delegate = new HttpComponentsClientHttpRequestFactory(httpClient).createRequest(newUri, httpMethod);

        Enumeration<String> headerNames = request.getHeaderNames();
        // 设置请求头
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            Enumeration<String> v = request.getHeaders(headerName);
            List<String> arr = new ArrayList<>();
            while (v.hasMoreElements()) {
                arr.add(v.nextElement());
            }
            delegate.getHeaders().addAll(headerName, arr);
        }
        StreamUtils.copy(request.getInputStream(), delegate.getBody());
        // 执行远程调用
        try (ClientHttpResponse clientHttpResponse = delegate.execute()) {
            response.setStatus(clientHttpResponse.getStatusCode().value());
            // 设置响应头
            clientHttpResponse.getHeaders().forEach((key, value) -> value.forEach(it -> {
                response.setHeader(key, it);
            }));
            StreamUtils.copy(clientHttpResponse.getBody(), response.getOutputStream());
        }
    }

}

Spring Boot使用HttpClient可以通过引入httpclient的POM依赖来实现。首先,在你的Spring Boot工程中,需要在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> ``` 接下来,你可以创建一个HttpClientController类,并在该类中定义不同的接口方法,如doGetNoParams和doPostNoParams。这些方法可以使用@GetMapping和@PostMapping注解来标注,分别表示GET和POST请求。例如: ```java @RestController @RequestMapping("/httpClient") public class HttpClientController { @Autowired private HttpClientService httpClientService; // GET请求接口不带参数 @GetMapping("/doGetNoParams") public String doGetNoParams() { return httpClientService.doGetNoParams(); } // POST请求接口不带参数 @PostMapping("/doPostNoParams") public String doPostNoParams() { return httpClientService.doPostNoParams(); } } ``` 在这个示例中,我们使用@Autowired将HttpClientService注入到HttpClientController中,然后在doGetNoParams和doPostNoParams方法中调用相应的HttpClientService方法来实现GET和POST请求。具体的请求逻辑可以在HttpClientService中实现。 这样,你就可以在Spring Boot使用HttpClient来进行HTTP请求了。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [「HttpClient」在 SpringBoot使用 HttpClient 实现 HTTP 请求](https://blog.csdn.net/wdj0311/article/details/121598212)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值