RestTemplate简洁使用指南

本文介绍了RestTemplate作为HTTP客户端的工具,它提供了简洁的方法进行GET、POST等操作。通过HttpEntity封装请求头和请求体,使用exchange方法能自定义请求并指定返回类型。了解更多详情,请参阅官方API。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RestTemplate

是什么

为HTTP请求/响应提供了一种模板,简化编写

常用方法

经常把RestTemplate作为一个bean使用,在业务中直接注入就可以使用,一般有get请求、post请求和普适请求(exchange)

  • restTemplate.getForEntity(url,String.class)
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
        String body = responseEntity.getBody();
        System.out.println(body);
  • restTemplate.postForEntity(url,request)
    notice: request参数一般是HttpEntity对象
    一般格式为HttpEntity(请求体,请求头)
    请求头的创建方法:
HttpHeaders httpHeaders = new HttpHeader();  
httpHeaders.set("xx","xx");

请求体一定要使用MultiValueMap类型:

MultiValueMap<String,Stirng> map = new MultivalueMap<>();  
map.add("参数名","xxx");  

然后将上面这两项封装到HttpEntity中

HttpEntity request = new HttpEntity(map,httpHeaders);
restTemplate.postForEntity("www.xxx.com",request);

最后返回的是一个ResponseEntity<T>

  • 最常用:restTemplate.exchange(url,HttpMethod,request,responseType)
    可自定义请求,比较常用
    HttpMehod: GET POST PUT DELETE等
    request: 请求实体=请求头+请求体 具体封装方法如上
    responseType: 返回类型,对一般网页是String.class
    具体实例:
String url = "http://xxxx.com";
// 设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
//设置user-agent 模拟浏览器访问
httpHeaders.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
//设置content-type为form-data
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//使用MultiValueMap封装请求体
MultiValueMap<String,String> map = new LinkedMultiValueMap<>();
map.add("name","xxxx");
// 创建http请求实体
HttpEntity request = new HttpEntity(map,httpHeaders);
//获取响应实体
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST,request,String.class);
return responseEntity.getBody();

详细

请见官网API:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值