使用RestTemplate实现http请求转发代理转发

使用RestTemplate实现http请求转发代理转发

在做微服务和单独集成等同构异构的项目过程中,可能会遇到做代理转发、请求转发等相关的功能,下面的代码(项目片段demo代码)可能具有一定的参与功能

下面代码仅供参考,具体还需要根据自己的项目情况对代码进行改造。可以在springMVC springboot项目中使用

import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;


/**
 * Created by zhangguoye on 2020/6/3
 * @author zhangguoye
 * 请求代理,请求转发
 * mapping的规则需要根据项目情况定义
 */
@RestController
@RequestMapping("/newportal")
public class HomeController {

    /** 以下请求服务器的相关信息,请在配置文件中进行配置 */
    private String uriSchema = "http";
    private String uriHostIp = "192.168.10.127";
    private Integer uriHostPort = 8088;
    /** mapping的规则需要根据项目情况定义 */
    private String uriRegex = "/newportal/api";

    /**
     * 向PC端转发get请求
     * @param request
     * @param response
     * @param httpMethod
     * @return
     * @throws URISyntaxException
     */
    @GetMapping(value = "/api/**")
    public ResponseEntity<Object> getPCWithParams(HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod) throws URISyntaxException {
        ResponseEntity res = request2PC(request, httpMethod, "");
        return res;
    }

    /**
     * 向PC端转发post请求  JSON数据请求
     * @param body  body为JSON数据
     * @param request
     * @param response
     * @param httpMethod
     * @return
     * @throws URISyntaxException
     */
    @PostMapping(value = "/api/**", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Object> postPCWithJson(@RequestBody Object body,HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod) throws URISyntaxException {
        ResponseEntity res = request2PC(request, httpMethod, body);
        return res;
    }

    /**
     * 向PC端转发post请求  formUrlEncode数据请求
     * @param formUrlEncode formUrlEncode数据
     * @param request
     * @param response
     * @param httpMethod
     * @return
     * @throws URISyntaxException
     */
    @PostMapping(value = "/api/**", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public ResponseEntity<Object> postPCWithFormUrlEncode(@RequestBody MultiValueMap<String, String> formUrlEncode, HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod) throws URISyntaxException {
        ResponseEntity res = request2PC(request, httpMethod, formUrlEncode);
        return res;
    }

    /**
     * 向PC端转发post请求  formData数据请求 文件上传请求
     * @param request
     * @param response
     * @param httpMethod
     * @return
     * @throws URISyntaxException
     */
    @PostMapping(value = "/api/**", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Object> postPCWithFormData(HttpServletRequest request, HttpServletResponse response, HttpMethod httpMethod) throws URISyntaxException {
//        ResponseEntity res = request2PC(request, httpMethod, "");
//        return res;
        return null;
    }

    /**
     * 向PC端转发请求
     * @param request  HttpServletRequest
     * @param httpMethod 请求方式
     * @param body 请求body
     * @return
     * @throws URISyntaxException
     */
    private ResponseEntity request2PC(HttpServletRequest request, HttpMethod httpMethod, Object body) throws URISyntaxException {
        String[] requestURIArr = request.getRequestURI().split(uriRegex);
        if (requestURIArr.length < 1) {
            throw new RuntimeException("请求路径异常!");
        }
        String requestURI = requestURIArr[1];
        URI thirdPartyApi = new URI(uriSchema, null, uriHostIp, uriHostPort, requestURI, request.getQueryString(), null);
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity httpEntity = new HttpEntity(body);
        ResponseEntity<Object> response = restTemplate.exchange(thirdPartyApi, httpMethod, httpEntity, Object.class);
        return  response;
    }

}

一篇RestTemplate使用说明(中文):https://my.oschina.net/sdlvzg/blog/1800395

如果能给你提供到帮助,希望能点个赞👍🏻

Spring Boot中可以通过组合使用代理服务器和HTTP请求转发实现代理转发。具体步骤如下: 1. 配置代理服务器 在application.properties文件中配置代理服务器的地址和端口号: ``` # 配置代理服务器地址和端口号 spring.proxies.host=proxy.example.com spring.proxies.port=8080 ``` 2. 创建RestTemplate对象 在创建RestTemplate对象时,需要设置代理服务器的地址和端口号: ```java @Configuration public class RestTemplateConfiguration { @Value("${spring.proxies.host}") private String proxyHost; @Value("${spring.proxies.port}") private int proxyPort; @Bean public RestTemplate restTemplate() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); requestFactory.setProxy(proxy); return new RestTemplate(requestFactory); } } ``` 3. 创建转发服务 创建一个转发服务,用于将HTTP请求转发到目标服务: ```java @RestController public class ForwardController { private final RestTemplate restTemplate; public ForwardController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @GetMapping("/forward") public String forward(HttpServletRequest request) { // 获取目标URL String url = request.getParameter("url"); // 发送HTTP请求获取响应 ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); // 返回响应 return responseEntity.getBody(); } } ``` 4. 创建代理服务 创建一个代理服务,用于接收HTTP请求并将请求转发转发服务: ```java @RestController public class ProxyController { private final RestTemplate restTemplate; public ProxyController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @GetMapping("/proxy") public String proxy(HttpServletRequest request) { // 获取转发URL String url = request.getParameter("url"); // 构造转发URL String forwardUrl = "http://localhost:8080/forward?url=" + url; // 发送HTTP请求获取响应 ResponseEntity<String> responseEntity = restTemplate.getForEntity(forwardUrl, String.class); // 返回响应 return responseEntity.getBody(); } } ``` 5. 配置路由规则 在application.properties文件中配置路由规则: ``` # 配置路由规则 spring.cloud.gateway.routes[0].id=proxy spring.cloud.gateway.routes[0].uri=http://localhost:8081 spring.cloud.gateway.routes[0].predicates[0]=Path=/proxy/** ``` 6. 启动服务 启动代理服务和转发服务,访问代理服务的URL即可实现代理转发。 以上就是使用Spring Boot实现代理转发的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值