1. 程式人生 > >springboot發送http請求

springboot發送http請求

local exchange 情況下 app media oot 下午 pri bsp

springboot中實現http請求調用api

  1. 創建發送http請求service層

    import org.springframework.http.*;
    import org.springframework.stereotype.Service;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.client.RestTemplate;
    
    /**
     * @Author 馮戰魁
     * @Date 2018/1/23 下午5:43
     */
    @Service
    public class HttpClient {
        public String client(String url, HttpMethod method, MultiValueMap<String, String> params){
            RestTemplate client = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //  請勿輕易改變此提交方式,大部分的情況下,提交方式都是表單提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
            //  執行HTTP請求
            ResponseEntity<String> response = client.exchange(url, HttpMethod.POST, requestEntity, String.class);
            return response.getBody();
        }
    }
  2. 添加本地測試url localhost:8080/hello

    import com.example.demo.service.HttpClient;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.*;
    import org.springframework.util.LinkedMultiValueMap;
    import org.springframework.util.MultiValueMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    
    /**
     * @Author 馮戰魁
     * @Date 2018/1/8 上午11:17
     */
    @RestController
    public class HelloController {
        @Autowired
        HttpClient httpClient;
        @RequestMapping("/hello")
        public String hello(){
            //api url地址
            String url = "http://xxxx";
            //post請求
            HttpMethod method =HttpMethod.POST;
            // 封裝參數,千萬不要替換為Map與HashMap,否則參數無法傳遞
            MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
            params.add("access_token", "xxxxx");
            //發送http請求並返回結果
            return httpClient.client(url,method,params);
        }
    }
  3. 訪問localhost:8080/hello查看調用結果

    curl http://localhost:8080/hello

springboot發送http請求