springboot(34) : 转发post请求

controller 



import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: liyue
 * @Date: 2022/11/22/21:19
 * @Description:
 */
@RestController
@Slf4j
public class ImageController {

    @Autowired
    private RestTemplate restTemplate;

    private static final String LOG_PATTERN = System.lineSeparator()
            + "    url:{}" + System.lineSeparator()
            + "    req:{}" + System.lineSeparator()
            + "   resp:{}" + System.lineSeparator()
            + "   timeConsuming:{}ms" + System.lineSeparator();

    @RequestMapping("/test")
    public Object test(HttpServletRequest request) {
        final String url = "http://192.168.1.1:7001/test";
        return post(url, request);
    }

    public JSONObject post(String url, HttpServletRequest request) {
        String param = null;
        try {
            param = getParameters(request).toJSONString();
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
            // 获取到请求头
            Enumeration<String> headerNames = request.getHeaderNames();
            HttpHeaders headers = new HttpHeaders();
            Map<String, String> headerMap = new HashMap<>();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String header = request.getHeader(headerName);
                headerMap.put(headerName, header);
                headers.add(headerName, header);
            }
            // 构造HttpEntity,新请求会携带本次请求的请求头
            HttpEntity<String> entity = new HttpEntity<>(param, headers);
            long currentTimeMillis = System.currentTimeMillis();
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            log.info(LOG_PATTERN, url, param, response.getBody(), System.currentTimeMillis() - currentTimeMillis);
            return JSONObject.parseObject(response.getBody());
        } catch (Exception e) {
            log.error("请求出错! \n    url:{}\n    req:{}", url, param, e);
            return null;
        }
    }

    //获取参数
    public static JSONObject getParameters(HttpServletRequest request) {
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            return jsonObject;
        } catch (Exception e) {
            log.error("获取json参数失败", e);
            return null;
        }
    }

}

Application

package com.alibaba.jihe.ln.image.start;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableScheduling
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

maven


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.14</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,当以POST方式请求控制器后,如果以转发形式跳转页面,会保持POST方式请求HTML静态资源,导致405错误。这是因为Spring Boot只允许GET方式请求静态资源。 为了解决这个问题,可以添加一个过滤器来实现对请求方法的过滤。通过设置"Access-Control-Allow-Methods"响应头,将允许的请求方法限定为GET和POST。同时,在过滤器中对请求进行过滤,只允许GET和POST请求通过,其他请求返回"Method Not Allowed"错误。 另外,有时候可能会误以为是控制器配置错误导致了405错误。但实际上,默认情况下,控制器使用@RequestMapping注解时是支持GET和POST请求的。因此,应该检查是否强制指定了POST方式,并相应地进行修改。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [SpringBootpost请求报405错误排坑](https://blog.csdn.net/m0_67394002/article/details/126114363)[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: 50%"] - *2* [SpringBoot中405异常](https://blog.csdn.net/qq_39720263/article/details/128120851)[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: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值