spring boot 請求json接口------RestTemplate的使用

1、需求:要請求對方提供的json接口,直接前端請求的話有跨域問題,因此從後端處理html

        1使用springboot的RestTemplate來實現,RestTemplate簡單的理解就是:簡化了發起 HTTP 請求以及處理響應的過程。前端

        2在springboot中配置RestTemplatejava

        

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    postForObjectweb

    

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.htmspring

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

相關文章
相關標籤/搜索