溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springboot發送http請求

發布時間:2020-07-22 22:04:27 來源:網絡 閱讀:79721 作者:無心低語 欄目:開發技術

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

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女