RestTemplate的请求方式

本文介绍了SpringBoot中使用RestTemplate进行HTTP请求的方法,包括GET、POST、PUT和DELETE。在启动类中配置RestTemplate,GET请求有getForEntity和getForObject,返回不同类型响应。POST请求有postForEntity和postForLocation,postForLocation返回新资源的URI。PUT请求的put方法无返回值,DELETE请求的delete同样无返回值。

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

SpringMVC提供 RestTemplate请求http接口,RestTemplate的底层可以使用第三方的http客户端工具实现http 的 请求,,常用的http客户端工具有Apache HttpClient、OkHttpClient等。

在SpringBoot启动类中配置 RestTemplate

@Bean
@LoadBalanced//开启负载均衡
public RestTemplate restTemplate() {
    //使用OkHttpClient完成http请求(性能比较出众)
    return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}

本文RestTemplate的常用方法如下图:
在这里插入图片描述

GET请求

1.getForEntity

返回的是ResponseEntity。

源码
    public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType) throws RestClientException {
        RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
        ResponseExtractor<ResponseEntity<T>> responseExtractor = this.responseEntityExtractor(responseType);
        return (ResponseEntity)nonNull(this.execute(url, HttpMethod.GET, requestCallback, responseExtractor));
    }

请求url和返回类型

@Test
public void testRestTemplate(){
    ResponseEntity<Map> forEntity = restTemplate.getForEntity("http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f", Map.class);
    Map body = forEntity.getBody();
    System.out.println(body);
}

2.getForObject

源码
    @Nullable
    public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException {
        RequestCallback requestCallback = this.acceptHeaderRequestCallback(responseType);
        HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor(responseType, this.getMessageConverters(), this.logger);
        return this.execute(url, HttpMethod.GET, requestCallback, responseExtractor);
    }

getForObject函数实际上是对getForEntity函数的进一步封装,返回的消息体的内容,返回HttpEntity的body。

POST请求

  1. postForEntity

  2. postForObject

  3. postForLocation

    @Nullable
    public URI postForLocation(URI url, @Nullable Object request) throws RestClientException {
        RequestCallback requestCallback = this.httpEntityCallback(request);
        HttpHeaders headers = (HttpHeaders)this.execute(url, HttpMethod.POST, requestCallback, this.headersExtractor());
        return headers != null ? headers.getLocation() : null;
    }
    

    @Nullable
    public URI getLocation() {
        String value = this.getFirst("Location");
        return value != null ? URI.create(value) : null;
    }

通过上面的源码可以看出postForLocation返回的是新资源的URI。

PUT请求

put
无返回值

DELETE请求

delete
无返回值

### 使用 `RestTemplate` 发送 HTTP 请求 #### 创建 `RestTemplate` 实例 可以通过调用无参构造函数来创建 `RestTemplate` 对象,在底层该对象会利用 `java.net` 包中的类来构建 HTTP 请求;当然也支持自定义请求工厂以改变其行为[^1]。 ```java // 默认构造器初始化 RestTemplate RestTemplate restTemplate = new RestTemplate(); ``` 对于更复杂的场景,比如需要配置连接池或者其他高级特性,则可以提供特定的 `ClientHttpRequestFactory` 来定制化实例: ```java HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setConnectTimeout(5000); // 设置超时时间 RestTemplate restTemplate = new RestTemplate(factory); ``` #### 执行 GET 请求并获取响应实体 下面展示了一个简单的例子,用于向服务器发起 GET 请求,并接收返回的数据作为字符串处理。 ```java String url = "http://example.com/api/resource"; ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); if (response.getStatusCode().is2xxSuccessful()) { System.out.println(response.getBody()); } else { System.err.println("Failed to fetch resource"); } ``` #### POST 请求提交 JSON 数据 当涉及到发送带有复杂结构体(如多层嵌套的对象)到服务端时,可以直接传递 Java 的 Map 或者 JSONObject 类型给 post 方法。虽然有观点认为仅限于使用 LinkedMultiValueMap,但实际上普通的 HashMap 同样适用,甚至还可以采用其他形式的数据容器[^2]。 这里给出一个完整的示例,演示如何通过 POST 方式上传包含多个字段的信息至远程接口: ```java import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; // 准备请求头信息 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); // 构建请求体数据 Map<String, Object> requestBody = new HashMap<>(); requestBody.put("name", "John Doe"); Map<String, Integer> ageInfo = Collections.singletonMap("age", 30); requestBody.put("details", ageInfo); // 封装成 HttpEntity 并执行POST操作 HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers); String apiUrl = "https://api.example.com/user/create"; ResponseEntity<UserDTO> result = restTemplate.postForEntity(apiUrl, requestEntity, UserDTO.class); System.out.println(result.getBody()); // 输出新创建用户的详情 ``` 在这个案例里,假设目标 API 接受的是 application/json 格式的输入流,并期望接收到的名字叫 name 和 details 这样的键值对参数。最后一步是解析来自服务器反馈的内容为预定义好的 DTO 类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值