Spring Boot 用 RestTemplate 发送HTTP 请求

Spring RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率

调用 RestTemplate 的默认构造函数,RestTemplate 对象在底层通过使用 java.net 包下的实现创建 HTTP 请求,可以通过使用 ClientHttpRequestFactory 指定不同的HTTP请求方式。默认使用 SimpleClientHttpRequestFactory,是 ClientHttpRequestFactory 实现类。


RestTemplate能大幅简化了提交表单数据的难度,并且附带了自动转换JSON数据的功能

使用RestTemplate 访问请求非常的简单粗暴无脑。例如:

RestTemplate restTemplate = new RestTemplate();
ResponseBean responseBean = restTemplate.postForObject(url, requestBean, ResponseBean.class);

 url, requestBean, ResponseBean.class 

这三个参数分别代表:请求地址、请求参数、HTTP响应被转换成的对象类型

requestBean 请求参数可以为空,ResponseBean 为返回值类型。

示例

   import org.springframework.web.client.RestTemplate;


    /**
     * 不带参数的请求示例
     * get 请求
     */
    // http 请求url,返回ReturnResult类型数据
    public ReturnResult request(String url) {
        RestTemplate restTemplate = new RestTemplate();
        ReturnResult result = restTemplate.getForObject(url, ReturnResult.class);
        return result;
    }


    /**
     * 带参数的请求示例
     * post 请求
     * 该示例你请求的接口:请求参数类型为json,返回类型为json
     */
    public static void main(String[] args) {
        String url = "http://127.0.0.1:8888/app/getCustInfo?token=d3eb9a9233e52948740d7ab8c3062d14";

        JSONObject json = new JSONObject();
        json.put("beginDate", "2021-01-17");
        json.put("endDate", "2021-06-22");
        json.put("custOutCode", "");
        json.put("pageNo", 1);
        json.put("pageSize", 5);

        RestTemplate restTemplate = new RestTemplate();
        JSONObject responseBean = restTemplate.postForObject(url, json, JSONObject.class);

        System.out.println(responseBean);
    }


补充:

感谢博客:SpringBoot ——— 使用RestTemplate发送带token的GET和POST请求_自傷無色丶的博客-CSDN博客_resttemplate设置token

带 Token 的Get请求示例:

 

Post 请求示例:

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;



public Result testPost(PostEntity postEntity,String token) {
 
        MediaType type = MediaType.parseMediaType("application/json");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        headers.add("Accept", MediaType.ALL_VALUE);
        headers.add("Authorization", token);
        JSONObject param = JSONUtil.parseObj(postEntity);
        HttpEntity<String> formEntity = new HttpEntity<String>(param.toString(), headers);
        ResponseEntity<Integer> responsebody = restTemplate.exchange(
                saveLeaseContractUrl,
                HttpMethod.POST,
                formEntity,
                Integer.class);
        Integer contractId = responsebody.getBody();

}

带Headers 的请求示例:jsons 为请求参数(json格式)

private CisResult httpSgpRequest(String url, JSONObject jsons) {
    log.info("向sgp请求的url为:{},参数为:{}", url, jsons);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accesskey", "d3eb9a9233e52948740d7eb8c3062d14");

    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<String> requestEntity = new HttpEntity<>(jsons.toString(), headers);
    ResponseEntity<String> responseEntity = restTemplate.exchange(
            url,
            HttpMethod.POST,
            requestEntity,
            String.class
    );
    JSONObject res = JSONObject.parseObject(responseEntity.getBody(), JSONObject.class);
    log.info("请求结果:{}", res);
    if (res != null) {
        if ("00".equals(res.get("resultCode"))) {
            return CisResult.defaultOk();
        }
        return CisResult.defaultCheckError(res.getString("resultMsg"));
    }
    return CisResult.defaultError();
}

补充示例:Java后台请求第三方系统接口

    public static String sendPost(String strUrl, String param, String token) {
        log.info("发送参数:" + param);
        StringBuilder result = new StringBuilder();
        try {
            // 创建连接
            URL url = new URL(strUrl);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 设置post提交形式
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("authorization", "Bearer " + token);
            connection.connect();
            // POST请求
            OutputStreamWriter oWriter = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8);
            BufferedWriter out = new BufferedWriter(oWriter);
            out.write(param);
            out.flush();
            oWriter.close();
            out.close();
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String lines;
            while ((lines = reader.readLine()) != null) {
                result.append(lines);
            }
            log.info("响应:" + result);
            reader.close();
            // 断开连接
            connection.disconnect();

        } catch (MalformedURLException e) {
            log.error("请求接口错误,检查地址或参数是否正确");
            log.error("异常原因", e);
            result = new StringBuilder();
        } catch (IOException e) {
            log.error("写入数据异常:", e);
            result = new StringBuilder();
        }
        return result.toString();
    }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值