天天看點

SpringBoot使用RestTemplate調用第三方接口

SpringBoot使用RestTemplate調用第三方接口

1.先引用pom.xml依賴

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </dependency>
           

這邊是JSONObject的包用來處理參數和傳回值,RestTemplate 不需要單獨引jar包,Springboot自己內建了

2.我這邊隻寫了POST請求的代碼

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

public class RestTemplateUtil {

    public static JSONObject sendPostRequest(String url, JSONObject params) {
        // 第一步 建立模闆
        RestTemplate restTemplate = new RestTemplate();
        // 請求頭部
        HttpHeaders headers = new HttpHeaders();
        // 送出方式
        // post請求體為body,是以我們這邊傳json
        // 是以傳參格式也必須為json
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 将請求頭部和參數合成一個請求
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(params, headers);
        JSONObject response = restTemplate.postForObject(url, requestEntity, JSONObject.class);
        return response;
    }

    public static void main(String[] args) {
        // 對方API路徑
        String url = "http://192.168.1.57:3444/api/token";
        // 參數
        JSONObject params = new JSONObject();
        params.put("username", "admin");
        params.put("password", "123456");
        JSONObject userInfo = sendPostRequest(url, params);
        System.out.println("api調用成功,jwtToken是:"+userInfo.get("jwtToken"));
    }

}