一、需求:要请求对方提供的json接口,直接前端请求的话有跨域问题,所以从后端处理

        1使用springboot的RestTemplate来实现,RestTemplate简单的理解就是:简化了发起 HTTP 请求以及处理响应的过程。

        2在springboot中配置RestTemplate

        

package com.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class HttpApiConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }
}

    3使用常用的post请求方法postForEntity    postForObject

    

package com.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/PortData")
public class PortDataController {

    //注入
    @Autowired
    private RestTemplate restTemplate;


    @RequestMapping("/FaceInfo")
    @ResponseBody
    public Object   faceInfo(String startTime,String endTime,Integer size ){
        String apiURL = "http://xx.xx.xx.xx:8094/face/cfStatistic";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);




        Map<String, Object> requestParam = new HashMap<>();

        requestParam.put("startTime", startTime);
        requestParam.put("endTime", endTime);
        requestParam.put("size", size);
        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(requestParam, headers);


        ResponseEntity<String> entity = restTemplate.postForEntity(apiURL, request, String.class);


        String body = entity.getBody();

        return body;


    }

}

参考:https://www.jb51.net/article/145618.htm

    https://www.cnblogs.com/wangbin2188/p/9204022.html

05-09 15:16