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 headerNames = request.getHeaderNames();
            HttpHeaders headers = new HttpHeaders();
            Map 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 entity = new HttpEntity<>(param, headers);
            long currentTimeMillis = System.currentTimeMillis();
            ResponseEntity 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


        
            org.projectlombok
            lombok
            1.18.14
            provided
        
        
            com.alibaba
            fastjson
            1.2.83
        

你可能感兴趣的:(#,springboot,spring,boot,java,转发请求,转发,post请求)