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"));
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_45452416/article/details/115113173