SpringBoot-RestTemplate

本文介绍了如何在SpringBoot中使用RestTemplate进行RESTful请求,包括GET和POST两种方式。GET请求涵盖了获取对象、数组、带参数的请求及文件请求;POST请求则涉及携带cookie、模拟表单提交、JSON数据提交以及通过URL发送POST请求。

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

摘要

SpringBoot提供RestTemplate作为Rest请求访问的客户端

使用

GET请求

1 获取对象
public User findById(Long id){
    return restTemplate.getForObject("http://localhost:8080/"+id,User.class)
}
2 获取数组
public List<User> getUsers(){
    return Arrays.asList(restTemplate.getForObject("http://localhost:8080/list".User[].class));
}
3 GET请求带有参数
public User[] find(String name,int age){
    Map<String,Object> param = Maps.newHashMap();
    param.put("name",name);
    param.put("age",age);
    return restTemplate.getForObject(
        "http://localhost:8080/serach?name={name}&age={age}",
        User[].class,
        param)
}
4 请求文件
String url = "";
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_OCTET_STREAM));
HttpEntity<String> request = new HttpEntity<>(headers);
ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, request, byte[].class);
byte[] bytes = response.getBody();

POST请求

1 请求携带cookie
String url= "";
HttpHeaders headers = new HttpHeaders();
List<String> cookies = new ArrayList<>();
cookies.add("mycookie=mycookie");
headers.put(HttpHeaders.COOKIE, cookies);
HttpEntity request = new HttpEntity(null, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
2 模拟提交表单
String url = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.add("username", "admin");
form.add("password", "admin");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class); 
3 模拟提交json
String url = "";
String json = "";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
HttpEntity<String> request = new HttpEntity<>(json, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
4 通过URL提交POST请求
String url = "http://localhost:8080/login?username={0}&password={1}";
url = MessageFormat.format(url, "admin", "admin");
restTemplate.postForEntity(url, null, String.class);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值