此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

REST 客户端

Spring 框架提供了以下选项来调用 REST 端点:spring-doc.cadn.net.cn

RestClient

RestClient是一个同步 HTTP 客户端,提供现代、流畅的 API。 它提供了对 HTTP 库的抽象,允许方便地从 Java 对象转换为 HTTP 请求,以及从 HTTP 响应创建对象。spring-doc.cadn.net.cn

创建RestClient

RestClient是使用静态create方法。 您还可以使用builder()以获取具有更多选项的构建器,例如指定要使用的 HTTP 库(请参阅客户端请求工厂)和要使用的消息转换器(请参阅HTTP 消息转换)、设置默认 URI、默认路径变量、默认请求标头或uriBuilderFactory,或者注册侦听器和初始值设定项。spring-doc.cadn.net.cn

创建(或构建)后,RestClient可以被多个线程安全地使用。spring-doc.cadn.net.cn

以下示例演示如何创建默认RestClient以及如何构建自定义 THE SCSI。spring-doc.cadn.net.cn

RestClient defaultClient = RestClient.create();

RestClient customClient = RestClient.builder()
  .requestFactory(new HttpComponentsClientHttpRequestFactory())
  .messageConverters(converters -> converters.add(new MyCustomMessageConverter()))
  .baseUrl("https://example.com")
  .defaultUriVariables(Map.of("variable", "foo"))
  .defaultHeader("My-Header", "Foo")
  .requestInterceptor(myCustomInterceptor)
  .requestInitializer(myCustomInitializer)
  .build();
val defaultClient = RestClient.create()

val customClient = RestClient.builder()
  .requestFactory(HttpComponentsClientHttpRequestFactory())
  .messageConverters { converters -> converters.add(MyCustomMessageConverter()) }
  .baseUrl("https://example.com")
  .defaultUriVariables(mapOf("variable" to "foo"))
  .defaultHeader("My-Header", "Foo")
  .requestInterceptor(myCustomInterceptor)
  .requestInitializer(myCustomInitializer)
  .build()

使用RestClient

使用RestClient,首先要指定的是要使用的 HTTP 方法。 这可以通过method(HttpMethod)或使用便捷方法get(),head(),post()等。spring-doc.cadn.net.cn

请求 URL

接下来,可以使用uri方法。 此步骤是可选的,如果RestClient配置了默认 URI。 URL 通常指定为String,其中包含可选的 URI 模板变量。 以下示例将 GET 请求配置为example.com/orders/42:spring-doc.cadn.net.cn

int id = 42;
restClient.get()
  .uri("https://example.com/orders/{id}", id)
  ....
val id = 42
restClient.get()
  .uri("https://example.com/orders/{id}", id)
  ...

函数还可用于更多控制,例如指定请求参数spring-doc.cadn.net.cn

默认情况下,String URL 是编码的,但这可以通过使用自定义uriBuilderFactory. URL 也可以随函数一起提供,也可以作为java.net.URI,这两者都未编码。 有关使用 URI 和编码 URI 的更多详细信息,请参阅 URI 链接spring-doc.cadn.net.cn

请求标头和正文

如有必要,可以通过添加请求标头来作 HTTP 请求header(String, String),headers(Consumer<HttpHeaders>或使用便捷方法accept(MediaType…​),acceptCharset(Charset…​)等等。 对于可以包含正文 (POST,PUTPATCH),还有其他方法可用:contentType(MediaType)contentLength(long).spring-doc.cadn.net.cn

请求正文本身可以由body(Object),它在内部使用 HTTP 消息转换。 或者,可以使用ParameterizedTypeReference,允许您使用泛型。 最后,可以将 body 设置为一个回调函数,该函数写入OutputStream.spring-doc.cadn.net.cn

检索响应

设置请求后,通过调用retrieve(). 可以使用body(Class)body(ParameterizedTypeReference)对于参数化类型(如 lists)。 这body方法将响应内容转换为各种类型——例如,字节可以转换为String、JSON 可以使用 Jackson 转换为对象,依此类推(请参阅 HTTP 消息转换)。spring-doc.cadn.net.cn

响应也可以转换为ResponseEntity,从而访问响应标头和正文。spring-doc.cadn.net.cn

此示例展示了如何RestClient可用于执行简单的GET请求。spring-doc.cadn.net.cn

String result = restClient.get() (1)
  .uri("https://example.com") (2)
  .retrieve() (3)
  .body(String.class); (4)

System.out.println(result); (5)
1 设置 GET 请求
2 指定要连接到的 URL
3 检索响应
4 将响应转换为字符串
5 打印结果
val result= restClient.get() (1)
  .uri("https://example.com") (2)
  .retrieve() (3)
  .body<String>() (4)

println(result) (5)
1 设置 GET 请求
2 指定要连接到的 URL
3 检索响应
4 将响应转换为字符串
5 打印结果

对响应状态代码和标头的访问是通过ResponseEntity:spring-doc.cadn.net.cn

ResponseEntity<String> result = restClient.get() (1)
  .uri("https://example.com") (1)
  .retrieve()
  .toEntity(String.class); (2)

System.out.println("Response status: " + result.getStatusCode()); (3)
System.out.println("Response headers: " + result.getHeaders()); (3)
System.out.println("Contents: " + result.getBody()); (3)
1 为指定 URL 设置 GET 请求
2 将响应转换为ResponseEntity
3 打印结果
val result = restClient.get() (1)
  .uri("https://example.com") (1)
  .retrieve()
  .toEntity<String>() (2)

println("Response status: " + result.statusCode) (3)
println("Response headers: " + result.headers) (3)
println("Contents: " + result.body) (3)
1 为指定 URL 设置 GET 请求
2 将响应转换为ResponseEntity
3 打印结果

RestClient可以使用 Jackson 库将 JSON 转换为对象。 请注意此示例中 URI 变量的用法,以及Acceptheader 设置为 JSON。spring-doc.cadn.net.cn

int id = ...;
Pet pet = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id) (1)
  .accept(APPLICATION_JSON) (2)
  .retrieve()
  .body(Pet.class); (3)
1 使用 URI 变量
2 Acceptheader 设置为application/json
3 将 JSON 响应转换为Petdomain 对象
val id = ...
val pet = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id) (1)
  .accept(APPLICATION_JSON) (2)
  .retrieve()
  .body<Pet>() (3)
1 使用 URI 变量
2 Acceptheader 设置为application/json
3 将 JSON 响应转换为Petdomain 对象

在下一个示例中,RestClient用于执行包含 JSON 的 POST 请求,该请求同样使用 Jackson 进行转换。spring-doc.cadn.net.cn

Pet pet = ... (1)
ResponseEntity<Void> response = restClient.post() (2)
  .uri("https://petclinic.example.com/pets/new") (2)
  .contentType(APPLICATION_JSON) (3)
  .body(pet) (4)
  .retrieve()
  .toBodilessEntity(); (5)
1 创建一个Petdomain 对象
2 设置 POST 请求和要连接到的 URL
3 Content-Typeheader 设置为application/json
4 pet作为请求正文
5 将响应转换为没有正文的响应实体。
val pet: Pet = ... (1)
val response = restClient.post() (2)
  .uri("https://petclinic.example.com/pets/new") (2)
  .contentType(APPLICATION_JSON) (3)
  .body(pet) (4)
  .retrieve()
  .toBodilessEntity() (5)
1 创建一个Petdomain 对象
2 设置 POST 请求和要连接到的 URL
3 Content-Typeheader 设置为application/json
4 pet作为请求正文
5 将响应转换为没有正文的响应实体。

错误处理

默认情况下,RestClient抛出RestClientException检索具有 4xx 或 5xx 状态代码的响应时。 可以使用onStatus.spring-doc.cadn.net.cn

String result = restClient.get() (1)
  .uri("https://example.com/this-url-does-not-exist") (1)
  .retrieve()
  .onStatus(HttpStatusCode::is4xxClientError, (request, response) -> { (2)
      throw new MyCustomRuntimeException(response.getStatusCode(), response.getHeaders()); (3)
  })
  .body(String.class);
1 为返回 404 状态代码的 URL 创建 GET 请求
2 为所有 4xx 状态代码设置状态处理程序
3 引发自定义异常
val result = restClient.get() (1)
  .uri("https://example.com/this-url-does-not-exist") (1)
  .retrieve()
  .onStatus(HttpStatusCode::is4xxClientError) { _, response -> (2)
    throw MyCustomRuntimeException(response.getStatusCode(), response.getHeaders()) } (3)
  .body<String>()
1 为返回 404 状态代码的 URL 创建 GET 请求
2 为所有 4xx 状态代码设置状态处理程序
3 引发自定义异常

交换

对于更高级的场景,RestClient通过exchange()方法,该 API 可以代替retrieve(). 使用exchange(),因为 exchange 函数已经提供了对完整响应的访问,从而允许您执行任何必要的错误处理。spring-doc.cadn.net.cn

Pet result = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id)
  .accept(APPLICATION_JSON)
  .exchange((request, response) -> { (1)
    if (response.getStatusCode().is4xxClientError()) { (2)
      throw new MyCustomRuntimeException(response.getStatusCode(), response.getHeaders()); (2)
    }
    else {
      Pet pet = convertResponse(response); (3)
      return pet;
    }
  });
1 exchange提供请求和响应
2 当响应具有 4xx 状态代码时引发异常
3 将响应转换为 Pet 域对象
val result = restClient.get()
  .uri("https://petclinic.example.com/pets/{id}", id)
  .accept(MediaType.APPLICATION_JSON)
  .exchange { request, response -> (1)
    if (response.getStatusCode().is4xxClientError()) { (2)
      throw MyCustomRuntimeException(response.getStatusCode(), response.getHeaders()) (2)
    } else {
      val pet: Pet = convertResponse(response) (3)
      pet
    }
  }
1 exchange提供请求和响应
2 当响应具有 4xx 状态代码时引发异常
3 将响应转换为 Pet 域对象

HTTP 消息转换

spring-webmodule 包含HttpMessageConverter用于读取和写入 HTTP 请求和响应正文的接口InputStreamOutputStream.HttpMessageConverter实例在客户端使用(例如,在RestClient)和服务器端(例如,在 Spring MVC REST 控制器中)。spring-doc.cadn.net.cn

框架中提供了主媒体 (MIME) 类型的具体实现,默认情况下,它们在RestClientRestTemplate在客户端,使用RequestMappingHandlerAdapter在服务器端(请参阅 配置消息转换器)。spring-doc.cadn.net.cn

的几种实现HttpMessageConverter如下所述。 请参阅HttpMessageConverterJavadoc以获取完整列表。 对于所有转换器,都使用默认媒体类型,但您可以通过设置supportedMediaTypes财产。spring-doc.cadn.net.cn

表 1.HttpMessageConverter 实现
消息转换器 描述

StringHttpMessageConverterspring-doc.cadn.net.cn

HttpMessageConverter可以读写的实现String实例。 默认情况下,此转换器支持所有文本媒体类型(text/*) 并使用Content-Typetext/plain.spring-doc.cadn.net.cn

FormHttpMessageConverterspring-doc.cadn.net.cn

HttpMessageConverter可以从 HTTP 请求和响应中读取和写入表单数据的实现。 默认情况下,此转换器读取和写入application/x-www-form-urlencodedmedia 类型。 表单数据从MultiValueMap<String, String>. 转换器还可以写入(但不能读取)从MultiValueMap<String, Object>. 默认情况下,multipart/form-data受支持。 可以支持其他多部分子类型来写入表单数据。 请参阅 javadoc 以获取FormHttpMessageConverter了解更多详情。spring-doc.cadn.net.cn

ByteArrayHttpMessageConverterspring-doc.cadn.net.cn

HttpMessageConverter可以从 HTTP 请求和响应中读取和写入字节数组的实现。 默认情况下,此转换器支持所有媒体类型 () 并使用*/*Content-Typeapplication/octet-stream. 您可以通过设置supportedMediaTypesproperty 和 overridridinggetContentType(byte[]).spring-doc.cadn.net.cn

MarshallingHttpMessageConverterspring-doc.cadn.net.cn

HttpMessageConverter实现,该实现可以使用 Spring 的MarshallerUnmarshallerabstractions 的org.springframework.oxm包。 此转换器需要一个MarshallerUnmarshaller才能使用。 您可以通过 constructor 或 bean 属性注入这些内容。 默认情况下,此转换器支持text/xmlapplication/xml.spring-doc.cadn.net.cn

MappingJackson2HttpMessageConverterspring-doc.cadn.net.cn

HttpMessageConverter可以使用 Jackson 的ObjectMapper. 您可以使用 Jackson 提供的注释根据需要自定义 JSON 映射。 当你需要进一步的控制时(对于需要为特定类型提供自定义 JSON 序列化器/反序列化器的情况),你可以注入一个自定义的ObjectMapper通过ObjectMapper财产。 默认情况下,此转换器支持application/json.spring-doc.cadn.net.cn

MappingJackson2XmlHttpMessageConverterspring-doc.cadn.net.cn

HttpMessageConverter可以使用 Jackson XML 扩展的XmlMapper. 您可以根据需要通过使用 JAXB 或 Jackson 提供的注释来自定义 XML 映射。 当你需要进一步的控制时(对于需要为特定类型提供自定义 XML 序列化器/反序列化器的情况),你可以注入一个自定义的XmlMapper通过ObjectMapper财产。 默认情况下,此转换器支持application/xml.spring-doc.cadn.net.cn

SourceHttpMessageConverterspring-doc.cadn.net.cn

HttpMessageConverter可以读写的实现javax.xml.transform.Source从 HTTP 请求和响应。 只DOMSource,SAXSourceStreamSource受支持。 默认情况下,此转换器支持text/xmlapplication/xml.spring-doc.cadn.net.cn

默认情况下,RestClientRestTemplate注册所有内置消息转换器,具体取决于 Classpath 上底层库的可用性。 您还可以将消息转换器设置为显式使用,方法是使用messageConverters()方法上的RestClientbuilder 或通过messageConverters的属性RestTemplate.spring-doc.cadn.net.cn

Jackson JSON 视图

要仅序列化对象属性的子集,您可以指定 Jackson JSON 视图,如下例所示:spring-doc.cadn.net.cn

MappingJacksonValue value = new MappingJacksonValue(new User("eric", "7!jd#h23"));
value.setSerializationView(User.WithoutPasswordView.class);

ResponseEntity<Void> response = restClient.post() // or RestTemplate.postForEntity
  .contentType(APPLICATION_JSON)
  .body(value)
  .retrieve()
  .toBodilessEntity();

多部分

要发送多部分数据,您需要提供MultiValueMap<String, Object>其值可以是Object对于部件内容,一个Resource对于文件部分,或者HttpEntity对于带有标题的 Part Content 进行翻译。 例如:spring-doc.cadn.net.cn

MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();

parts.add("fieldPart", "fieldValue");
parts.add("filePart", new FileSystemResource("...logo.png"));
parts.add("jsonPart", new Person("Jason"));

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_XML);
parts.add("xmlPart", new HttpEntity<>(myBean, headers));

// send using RestClient.post or RestTemplate.postForEntity

在大多数情况下,您不必指定Content-Type对于每个部分。 内容类型是根据HttpMessageConverter选择将其序列化,或者在Resource,具体取决于文件扩展名。 如有必要,您可以显式提供MediaType替换为HttpEntity包装纸。spring-doc.cadn.net.cn

一旦MultiValueMap已准备就绪,您可以将其用作POSTrequest, 使用RestClient.post().body(parts)(或RestTemplate.postForObject).spring-doc.cadn.net.cn

如果MultiValueMap包含至少一个非String值、Content-Type设置为multipart/form-dataFormHttpMessageConverter. 如果MultiValueMap具有Stringvalues 中,Content-Type默认为application/x-www-form-urlencoded. 如有必要,Content-Type也可以显式设置。spring-doc.cadn.net.cn

客户端请求工厂

要执行 HTTP 请求,RestClient使用客户端 HTTP 库。 这些库通过ClientRequestFactory接口。 有多种实现可供选择:spring-doc.cadn.net.cn

如果未指定请求工厂,则当RestClient构建时,它将使用 Apache 或 JettyHttpClient如果它们在 Classpath 上可用。 否则,如果java.net.http模块,它将使用 Java 的HttpClient. 最后,它将采用简单的默认值。spring-doc.cadn.net.cn

请注意,SimpleClientHttpRequestFactory在访问表示错误的响应的状态(例如 401)时,可能会引发异常。 如果这是一个问题,请使用任何替代请求工厂。

WebClient

WebClient是执行 HTTP 请求的非阻塞反应式客户端。它是 在 5.0 中引入,并提供了RestTemplate,支持 同步、异步和流式处理方案。spring-doc.cadn.net.cn

WebClient支持以下内容:spring-doc.cadn.net.cn

有关更多详细信息,请参阅 WebClientspring-doc.cadn.net.cn

RestTemplate

RestTemplate以经典的 Spring Template 类的形式通过 HTTP 客户端库提供高级 API。 它公开了以下重载方法组:spring-doc.cadn.net.cn

RestClient为同步 HTTP 访问提供更现代的 API。 对于异步和流式处理方案,请考虑反应式 WebClient
表 2.RestTemplate 方法
“方法”组 描述

getForObjectspring-doc.cadn.net.cn

通过 GET 检索表示形式。spring-doc.cadn.net.cn

getForEntityspring-doc.cadn.net.cn

检索ResponseEntity(即 status、headers 和 body)。spring-doc.cadn.net.cn

headForHeadersspring-doc.cadn.net.cn

使用 HEAD 检索资源的所有标头。spring-doc.cadn.net.cn

postForLocationspring-doc.cadn.net.cn

使用 POST 创建新资源并返回Location标头。spring-doc.cadn.net.cn

postForObjectspring-doc.cadn.net.cn

使用 POST 创建新资源,并从响应中返回表示形式。spring-doc.cadn.net.cn

postForEntityspring-doc.cadn.net.cn

使用 POST 创建新资源,并从响应中返回表示形式。spring-doc.cadn.net.cn

putspring-doc.cadn.net.cn

使用 PUT 创建或更新资源。spring-doc.cadn.net.cn

patchForObjectspring-doc.cadn.net.cn

使用 PATCH 更新资源并从响应中返回表示形式。 请注意,JDKHttpURLConnection不支持PATCH,但 Apache HttpComponents 和其他组件可以。spring-doc.cadn.net.cn

deletespring-doc.cadn.net.cn

使用 DELETE 删除指定 URI 处的资源。spring-doc.cadn.net.cn

optionsForAllowspring-doc.cadn.net.cn

使用 ALLOW 检索资源允许的 HTTP 方法。spring-doc.cadn.net.cn

exchangespring-doc.cadn.net.cn

上述方法的更通用(且不那么固执己见)版本,可在需要时提供额外的灵活性。 它接受一个RequestEntity(包括 HTTP 方法、URL、标头和正文作为输入)并返回一个ResponseEntity.spring-doc.cadn.net.cn

这些方法允许使用ParameterizedTypeReference而不是Class以指定 具有泛型的响应类型。spring-doc.cadn.net.cn

executespring-doc.cadn.net.cn

执行请求的最通用方式,可完全控制请求 通过回调接口进行准备和响应提取。spring-doc.cadn.net.cn

初始化

RestTemplate使用与RestClient. 默认情况下,它使用SimpleClientHttpRequestFactory,但这可以通过构造函数进行更改。 参见 客户端请求工厂spring-doc.cadn.net.cn

RestTemplate可以进行检测以实现可观测性,以便生成指标和跟踪。 请参阅 RestTemplate 可观察性支持部分。

身体

传入和返回的对象RestTemplate方法在 HTTP 消息的帮助下与 HTTP 消息相互转换HttpMessageConverter,请参阅 HTTP 消息转换spring-doc.cadn.net.cn

迁移自RestTemplateRestClient

下表显示了RestClient的等效项RestTemplate方法。 它可用于从后者迁移到前者。spring-doc.cadn.net.cn

表 3.RestTemplate 方法的 RestClient 等效项
RestTemplate方法 RestClient等效

getForObject(String, Class, Object…​)spring-doc.cadn.net.cn

get() .uri(String, Object…​) .retrieve() .body(Class)spring-doc.cadn.net.cn

getForObject(String, Class, Map)spring-doc.cadn.net.cn

get() .uri(String, Map) .retrieve() .body(Class)spring-doc.cadn.net.cn

getForObject(URI, Class)spring-doc.cadn.net.cn

get() .uri(URI) .retrieve() .body(Class)spring-doc.cadn.net.cn

getForEntity(String, Class, Object…​)spring-doc.cadn.net.cn

get() .uri(String, Object…​) .retrieve() .toEntity(Class)spring-doc.cadn.net.cn

getForEntity(String, Class, Map)spring-doc.cadn.net.cn

get() .uri(String, Map) .retrieve() .toEntity(Class)spring-doc.cadn.net.cn

getForEntity(URI, Class)spring-doc.cadn.net.cn

get() .uri(URI) .retrieve() .toEntity(Class)spring-doc.cadn.net.cn

headForHeaders(String, Object…​)spring-doc.cadn.net.cn

head() .uri(String, Object…​) .retrieve() .toBodilessEntity() .getHeaders()spring-doc.cadn.net.cn

headForHeaders(String, Map)spring-doc.cadn.net.cn

head() .uri(String, Map) .retrieve() .toBodilessEntity() .getHeaders()spring-doc.cadn.net.cn

headForHeaders(URI)spring-doc.cadn.net.cn

head() .uri(URI) .retrieve() .toBodilessEntity() .getHeaders()spring-doc.cadn.net.cn

postForLocation(String, Object, Object…​)spring-doc.cadn.net.cn

post() .uri(String, Object…​) .body(Object).retrieve() .toBodilessEntity() .getLocation()spring-doc.cadn.net.cn

postForLocation(String, Object, Map)spring-doc.cadn.net.cn

post() .uri(String, Map) .body(Object) .retrieve() .toBodilessEntity() .getLocation()spring-doc.cadn.net.cn

postForLocation(URI, Object)spring-doc.cadn.net.cn

post() .uri(URI) .body(Object) .retrieve() .toBodilessEntity() .getLocation()spring-doc.cadn.net.cn

postForObject(String, Object, Class, Object…​)spring-doc.cadn.net.cn

post() .uri(String, Object…​) .body(Object) .retrieve() .body(Class)spring-doc.cadn.net.cn

postForObject(String, Object, Class, Map)spring-doc.cadn.net.cn

post() .uri(String, Map) .body(Object) .retrieve() .body(Class)spring-doc.cadn.net.cn

postForObject(URI, Object, Class)spring-doc.cadn.net.cn

post() .uri(URI) .body(Object) .retrieve() .body(Class)spring-doc.cadn.net.cn

postForEntity(String, Object, Class, Object…​)spring-doc.cadn.net.cn

post() .uri(String, Object…​) .body(Object) .retrieve() .toEntity(Class)spring-doc.cadn.net.cn

postForEntity(String, Object, Class, Map)spring-doc.cadn.net.cn

post() .uri(String, Map) .body(Object) .retrieve() .toEntity(Class)spring-doc.cadn.net.cn

postForEntity(URI, Object, Class)spring-doc.cadn.net.cn

post() .uri(URI) .body(Object) .retrieve() .toEntity(Class)spring-doc.cadn.net.cn

put(String, Object, Object…​)spring-doc.cadn.net.cn

put() .uri(String, Object…​) .body(Object) .retrieve() .toBodilessEntity()spring-doc.cadn.net.cn

put(String, Object, Map)spring-doc.cadn.net.cn

put() .uri(String, Map) .body(Object) .retrieve() .toBodilessEntity()spring-doc.cadn.net.cn

put(URI, Object)spring-doc.cadn.net.cn

put() .uri(URI) .body(Object) .retrieve() .toBodilessEntity()spring-doc.cadn.net.cn

patchForObject(String, Object, Class, Object…​)spring-doc.cadn.net.cn

patch() .uri(String, Object…​) .body(Object) .retrieve() .body(Class)spring-doc.cadn.net.cn

patchForObject(String, Object, Class, Map)spring-doc.cadn.net.cn

patch() .uri(String, Map) .body(Object) .retrieve() .body(Class)spring-doc.cadn.net.cn

patchForObject(URI, Object, Class)spring-doc.cadn.net.cn

patch() .uri(URI) .body(Object) .retrieve() .body(Class)spring-doc.cadn.net.cn

delete(String, Object…​)spring-doc.cadn.net.cn

delete() .uri(String, Object…​) .retrieve() .toBodilessEntity()spring-doc.cadn.net.cn

delete(String, Map)spring-doc.cadn.net.cn

delete() .uri(String, Map) .retrieve() .toBodilessEntity()spring-doc.cadn.net.cn

delete(URI)spring-doc.cadn.net.cn

delete() .uri(URI) .retrieve() .toBodilessEntity()spring-doc.cadn.net.cn

optionsForAllow(String, Object…​)spring-doc.cadn.net.cn

options() .uri(String, Object…​) .retrieve() .toBodilessEntity() .getAllow()spring-doc.cadn.net.cn

optionsForAllow(String, Map)spring-doc.cadn.net.cn

options() .uri(String, Map) .retrieve() .toBodilessEntity() .getAllow()spring-doc.cadn.net.cn

optionsForAllow(URI)spring-doc.cadn.net.cn

options() .uri(URI) .retrieve() .toBodilessEntity() .getAllow()spring-doc.cadn.net.cn

exchange(String, HttpMethod, HttpEntity, Class, Object…​)spring-doc.cadn.net.cn

method(HttpMethod) .uri(String, Object…​) .headers(Consumer<HttpHeaders>) .body(Object) .retrieve() .toEntity(Class) [1]spring-doc.cadn.net.cn

exchange(String, HttpMethod, HttpEntity, Class, Map)spring-doc.cadn.net.cn

method(HttpMethod) .uri(String, Map) .headers(Consumer<HttpHeaders>) .body(Object) .retrieve() .toEntity(Class) [1]spring-doc.cadn.net.cn

exchange(URI, HttpMethod, HttpEntity, Class)spring-doc.cadn.net.cn

method(HttpMethod) .uri(URI) .headers(Consumer<HttpHeaders>) .body(Object) .retrieve() .toEntity(Class) [1]spring-doc.cadn.net.cn

exchange(String, HttpMethod, HttpEntity, ParameterizedTypeReference, Object…​)spring-doc.cadn.net.cn

method(HttpMethod) .uri(String, Object…​) .headers(Consumer<HttpHeaders>) .body(Object) .retrieve() .toEntity(ParameterizedTypeReference) [1]spring-doc.cadn.net.cn

exchange(String, HttpMethod, HttpEntity, ParameterizedTypeReference, Map)spring-doc.cadn.net.cn

method(HttpMethod) .uri(String, Map) .headers(Consumer<HttpHeaders>) .body(Object) .retrieve() .toEntity(ParameterizedTypeReference) [1]spring-doc.cadn.net.cn

exchange(URI, HttpMethod, HttpEntity, ParameterizedTypeReference)spring-doc.cadn.net.cn

method(HttpMethod) .uri(URI) .headers(Consumer<HttpHeaders>) .body(Object) .retrieve() .toEntity(ParameterizedTypeReference) [1]spring-doc.cadn.net.cn

exchange(RequestEntity, Class)spring-doc.cadn.net.cn

method(HttpMethod) .uri(URI) .headers(Consumer<HttpHeaders>) .body(Object) .retrieve() .toEntity(Class) [2]spring-doc.cadn.net.cn

exchange(RequestEntity, ParameterizedTypeReference)spring-doc.cadn.net.cn

method(HttpMethod) .uri(URI) .headers(Consumer<HttpHeaders>) .body(Object) .retrieve() .toEntity(ParameterizedTypeReference) [2]spring-doc.cadn.net.cn

execute(String, HttpMethod, RequestCallback, ResponseExtractor, Object…​)spring-doc.cadn.net.cn

method(HttpMethod) .uri(String, Object…​) .exchange(ExchangeFunction)spring-doc.cadn.net.cn

execute(String, HttpMethod, RequestCallback, ResponseExtractor, Map)spring-doc.cadn.net.cn

method(HttpMethod) .uri(String, Map) .exchange(ExchangeFunction)spring-doc.cadn.net.cn

execute(URI, HttpMethod, RequestCallback, ResponseExtractor)spring-doc.cadn.net.cn

method(HttpMethod) .uri(URI) .exchange(ExchangeFunction)spring-doc.cadn.net.cn

HTTP 接口

Spring Framework 允许您将 HTTP 服务定义为 Java 接口,其中@HttpExchange方法。您可以将此类接口传递给HttpServiceProxyFactory创建通过 HTTP 客户端(如RestClientWebClient.您还可以从@Controller服务器 请求处理。spring-doc.cadn.net.cn

首先使用@HttpExchange方法:spring-doc.cadn.net.cn

interface RepositoryService {

	@GetExchange("/repos/{owner}/{repo}")
	Repository getRepository(@PathVariable String owner, @PathVariable String repo);

	// more HTTP exchange methods...

}

现在,您可以创建一个代理,在调用方法时执行请求。spring-doc.cadn.net.cn

RestClient:spring-doc.cadn.net.cn

RestClient restClient = RestClient.builder().baseUrl("https://api.github.com/").build();
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();

RepositoryService service = factory.createClient(RepositoryService.class);

WebClient:spring-doc.cadn.net.cn

WebClient webClient = WebClient.builder().baseUrl("https://api.github.com/").build();
WebClientAdapter adapter = WebClientAdapter.create(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();

RepositoryService service = factory.createClient(RepositoryService.class);

RestTemplate:spring-doc.cadn.net.cn

RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(new DefaultUriBuilderFactory("https://api.github.com/"));
RestTemplateAdapter adapter = RestTemplateAdapter.create(restTemplate);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();

RepositoryService service = factory.createClient(RepositoryService.class);

@HttpExchange在类型级别受支持,它适用于所有方法:spring-doc.cadn.net.cn

@HttpExchange(url = "/repos/{owner}/{repo}", accept = "application/vnd.github.v3+json")
interface RepositoryService {

	@GetExchange
	Repository getRepository(@PathVariable String owner, @PathVariable String repo);

	@PatchExchange(contentType = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
	void updateRepository(@PathVariable String owner, @PathVariable String repo,
			@RequestParam String name, @RequestParam String description, @RequestParam String homepage);

}

方法参数

带注释的 HTTP 交换方法支持灵活的方法签名,包括以下内容 方法参数:spring-doc.cadn.net.cn

Method 参数 描述

URIspring-doc.cadn.net.cn

动态设置请求的 URL,覆盖注释的url属性。spring-doc.cadn.net.cn

UriBuilderFactoryspring-doc.cadn.net.cn

提供UriBuilderFactory以展开 URI 模板和 URI 变量。 实际上,将UriBuilderFactory(及其基 URL)的 URL。spring-doc.cadn.net.cn

HttpMethodspring-doc.cadn.net.cn

动态设置请求的 HTTP 方法,覆盖注释的method属性spring-doc.cadn.net.cn

@RequestHeaderspring-doc.cadn.net.cn

添加一个或多个请求标头。参数可以是Map<String, ?>MultiValueMap<String, ?>对于多个标头,一个Collection<?>的值,或者 individual value 的非 String 值支持类型转换。spring-doc.cadn.net.cn

@PathVariablespring-doc.cadn.net.cn

在请求 URL 中添加用于扩展占位符的变量。参数可以是Map<String, ?>具有多个变量或单个值。类型转换 支持非 String 值。spring-doc.cadn.net.cn

@RequestAttributespring-doc.cadn.net.cn

提供Object添加为 request 属性。仅支持WebClient.spring-doc.cadn.net.cn

@RequestBodyspring-doc.cadn.net.cn

将请求的主体作为要序列化的对象或 反应式流PublisherMono,Flux或任何其他异步类型支持的 通过配置的ReactiveAdapterRegistry.spring-doc.cadn.net.cn

@RequestParamspring-doc.cadn.net.cn

添加一个或多个请求参数。参数可以是Map<String, ?>MultiValueMap<String, ?>如果有多个参数,则Collection<?>of 值或 单个值。非 String 值支持类型转换。spring-doc.cadn.net.cn

什么时候"content-type"设置为"application/x-www-form-urlencoded"请求 参数在请求正文中编码。否则,它们将被添加为 URL 查询 参数。spring-doc.cadn.net.cn

@RequestPartspring-doc.cadn.net.cn

添加请求部分,可以是 String (表单字段),Resource(文件部分)、 对象(要编码的实体,例如作为 JSON)、HttpEntity(部分内容和标题)、 弹簧Part或 Reactive StreamsPublisher属于上述任何一项。spring-doc.cadn.net.cn

MultipartFilespring-doc.cadn.net.cn

MultipartFile,通常用于 Spring MVC 控制器 其中,它表示上传的文件。spring-doc.cadn.net.cn

@CookieValuespring-doc.cadn.net.cn

添加一个或多个 Cookie。参数可以是Map<String, ?>MultiValueMap<String, ?>对于多个 Cookie,则Collection<?>的值,或者 individual value 的非 String 值支持类型转换。spring-doc.cadn.net.cn

返回值

支持的返回值取决于底层客户端。spring-doc.cadn.net.cn

适应HttpExchangeAdapterRestClientRestTemplate支持同步返回值:spring-doc.cadn.net.cn

方法返回值 描述

voidspring-doc.cadn.net.cn

执行给定的请求。spring-doc.cadn.net.cn

HttpHeadersspring-doc.cadn.net.cn

执行给定的请求并返回响应标头。spring-doc.cadn.net.cn

<T>spring-doc.cadn.net.cn

执行给定的请求并将响应内容解码为声明的返回类型。spring-doc.cadn.net.cn

ResponseEntity<Void>spring-doc.cadn.net.cn

执行给定的请求并返回一个ResponseEntity替换为 Status 和 Headers。spring-doc.cadn.net.cn

ResponseEntity<T>spring-doc.cadn.net.cn

执行给定的请求,将响应内容解码为声明的返回类型,然后 返回一个ResponseEntity替换为 status、Headers 和 Decoded body。spring-doc.cadn.net.cn

适应ReactorHttpExchangeAdapterWebClient,支持以上所有 以及反应式变体。下表显示了 Reactor 类型,但您也可以使用 其他响应式类型,这些类型通过ReactiveAdapterRegistry:spring-doc.cadn.net.cn

方法返回值 描述

Mono<Void>spring-doc.cadn.net.cn

执行给定的请求,并发布响应内容(如果有)。spring-doc.cadn.net.cn

Mono<HttpHeaders>spring-doc.cadn.net.cn

执行给定的请求,释放响应内容(如果有),并返回 响应标头。spring-doc.cadn.net.cn

Mono<T>spring-doc.cadn.net.cn

执行给定的请求并将响应内容解码为声明的返回类型。spring-doc.cadn.net.cn

Flux<T>spring-doc.cadn.net.cn

执行给定的请求,并将响应内容解码为声明的 元素类型。spring-doc.cadn.net.cn

Mono<ResponseEntity<Void>>spring-doc.cadn.net.cn

执行给定的请求,并释放响应内容(如果有),并返回一个ResponseEntity替换为 Status 和 Headers。spring-doc.cadn.net.cn

Mono<ResponseEntity<T>>spring-doc.cadn.net.cn

执行给定的请求,将响应内容解码为声明的返回类型,然后 返回一个ResponseEntity替换为 status、Headers 和 Decoded body。spring-doc.cadn.net.cn

Mono<ResponseEntity<Flux<T>>spring-doc.cadn.net.cn

执行给定的请求,将响应内容解码为声明的 元素类型,并返回一个ResponseEntity替换为 status、headers 和 decoded 响应正文流。spring-doc.cadn.net.cn

默认情况下,同步返回值的超时时间ReactorHttpExchangeAdapter取决于底层 HTTP 客户端的配置方式。您可以设置blockTimeout值,但我们建议依赖 底层 HTTP 客户端,它在较低级别运行并提供更多控制。spring-doc.cadn.net.cn

错误处理

要自定义错误响应处理,您需要配置底层 HTTP 客户端。spring-doc.cadn.net.cn

RestClient:spring-doc.cadn.net.cn

默认情况下,RestClient提高RestClientException对于 4xx 和 5xx HTTP 状态代码。 要自定义此功能,请注册适用于所有响应的响应状态处理程序 通过客户端执行:spring-doc.cadn.net.cn

RestClient restClient = RestClient.builder()
		.defaultStatusHandler(HttpStatusCode::isError, (request, response) -> ...)
		.build();

RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();

有关更多详细信息和选项(例如禁止显示错误状态代码),请参阅 JavadocdefaultStatusHandlerRestClient.Builder.spring-doc.cadn.net.cn

WebClient:spring-doc.cadn.net.cn

默认情况下,WebClient提高WebClientResponseException对于 4xx 和 5xx HTTP 状态代码。 要自定义此功能,请注册适用于所有响应的响应状态处理程序 通过客户端执行:spring-doc.cadn.net.cn

WebClient webClient = WebClient.builder()
		.defaultStatusHandler(HttpStatusCode::isError, resp -> ...)
		.build();

WebClientAdapter adapter = WebClientAdapter.create(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(adapter).build();

有关更多详细信息和选项(例如禁止显示错误状态代码),请参阅 JavadocdefaultStatusHandlerWebClient.Builder.spring-doc.cadn.net.cn

RestTemplate:spring-doc.cadn.net.cn

默认情况下,RestTemplate提高RestClientException对于 4xx 和 5xx HTTP 状态代码。 要自定义此设置,请注册一个适用于所有响应的错误处理程序 通过客户端执行:spring-doc.cadn.net.cn

RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(myErrorHandler);

RestTemplateAdapter adapter = RestTemplateAdapter.create(restTemplate);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();

有关更多详细信息和选项,请参阅 JavadocsetErrorHandlerRestTemplate和 这ResponseErrorHandler等级制度。spring-doc.cadn.net.cn


1.HttpEntityheaders 和 body 必须提供给RestClient通过headers(Consumer<HttpHeaders>)body(Object).
2.RequestEntitymethod、URI、headers 和 body 必须提供给RestClient通过method(HttpMethod),uri(URI),headers(Consumer<HttpHeaders>)body(Object).