RestTemplate
org.springframework.web.client.RestTemplate
是 Spring Framework 提供的一个用于发送 HTTP 请求并处理 HTTP 响应的类。它是 Spring 提供的一种方便的方式,用于与 RESTful web 服务进行通信。使用 RestTemplate
,您可以执行 GET、POST、PUT、DELETE 等各种 HTTP 方法,并可以发送和接收 JSON、XML、表单数据等不同类型的数据。它提供了许多方法来简化与 RESTful 服务的交互,例如 getForObject()
、postForObject()
、exchange()
等。通过使用 RestTemplate
,您可以轻松地编写代码来访问和操作外部的 RESTful 服务。
CloseableHttpClient client = HttpClientBuilder.create()
.setSSLContext(...)
.setSSLSocketFactory(...)
.setDefaultCredentialsProvider(...)
.useSystemProperties()
.build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
RestTemplate template = new RestTemplate();
template.setRequestFactory(factory);
// 发送请求
buildRestTemplate().postForObject(...);
这代码片段是使用 Apache HttpClient 库创建一个 `CloseableHttpClient` 实例的示例,并在创建过程中进行了一些配置:
- `setSSLContext(create())`: 设置 SSL 上下文,通常用于配置 SSL/TLS 相关的参 数。在这里,`create()` 方法应该返回一个 `SSLContext` 对象。
- `setSSLSocketFactory()`: 设置 SSL 套接字工厂,通常用于自定义 SSL/TLS 握手过程。在这里,您需要提供一个实现了 `javax.net.ssl.SSLSocketFactory` 接口的对象。
- `setDefaultCredentialsProvider(provider)`: 设置默认的凭据提供者,允许您在发起请求时提供身份验证凭据。
- `useSystemProperties()`: 启用系统属性,允许 HttpClient 使用系统级别的配置,例如代理设置等。
- `build()`: 构建 `CloseableHttpClient` 实例,完成配置并准备好用于执行 HTTP 请求。
这样配置的 `CloseableHttpClient` 可以用于发送带有 SSL/TLS 配置和身份验证凭据的 HTTP 请求。请注意,确保适当处理敏感信息,如身份验证凭据,以确保安全性。
`HttpComponentsClientHttpRequestFactory` 和 `HttpClient` 之间的关系是这样的:
1. **HttpComponentsClientHttpRequestFactory**:它是 Spring Framework 中的一个类,用于在 Spring 的 RestTemplate 中创建 HTTP 请求的工厂。它基于 Apache HttpComponents 库实现,并提供了一种将 Apache HttpClient 整合到 Spring 应用程序中的方式。`HttpComponentsClientHttpRequestFactory` 实现了 Spring 的 `ClientHttpRequestFactory` 接口,允许 RestTemplate 使用 Apache HttpClient 来执行 HTTP 请求。
2. **HttpClient**:它是 Apache HttpComponents 库中的一个接口,用于发送 HTTP 请求和处理 HTTP 响应。`HttpClient` 接口定义了执行 HTTP 请求的方法,包括 GET、POST、PUT、DELETE 等,并提供了各种配置选项,例如连接超时、读取超时、连接池大小等。Apache HttpComponents 库还提供了 `CloseableHttpClient` 接口的默认实现,用于创建可关闭的 HTTP 客户端实例。
因此,`HttpComponentsClientHttpRequestFactory` 实际上是在 Spring Framework 中使用 Apache HttpClient 的一种机制。通过将 `HttpComponentsClientHttpRequestFactory` 注入到 RestTemplate 中,您可以利用 Apache HttpClient 的强大功能来执行各种 HTTP 操作,并且可以与 Spring 应用程序无缝集成。
http.auth.auth-cache
是 Apache HttpComponents 中 HttpClient 配置的一个属性,用于启用或禁用认证缓存。当启用认证缓存时,HttpClient 将会缓存先前进行过的认证,以便在后续的请求中重用已经进行过的认证信息,从而避免重复进行身份验证过程。
认证缓存对于降低网络开销和提高性能是非常有用的。例如,在进行多次请求到同一服务器时,如果服务器要求进行身份验证,启用认证缓存可以避免每次请求都重新进行完整的身份验证流程,而是可以重用先前成功的认证信息。
您可以通过将 http.auth.auth-cache
设置为 true
来启用认证缓存,或者设置为 false
来禁用认证缓存。默认情况下,认证缓存是启用的。例如,在 HttpClient 的配置中,您可以通过以下方式启用认证缓存:
httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
.setStaleConnectionCheckEnabled(true)
.build())
.setDefaultCredentialsProvider(credentialsProvider)
.setDefaultAuthCache(new BasicAuthCache())
.build();
在此示例中,setDefaultAuthCache(new BasicAuthCache())
将会启用基本的认证缓存。
问题:调用exchange方法报错org.springframework.web.client.HttpClientErrorException$NotAcceptable: 406 Not Acceptable: “{“error”:“Content-Type header [text/plain;charset=ISO-8859-1] is not supported”,“status”:406}”
原因是没有设置contentType。
headers.setContentType(MediaType.APPLICATION_JSON)
是一个Java语句,用于设置HTTP请求头中的 Content-Type 属性为 “application/json”。在这里,headers
是一个 org.springframework.http.HttpHeaders
对象,MediaType.APPLICATION_JSON
是 Spring Framework 提供的表示 JSON 内容类型的常量。
这行代码的作用是告诉服务器,请求体中的数据是 JSON 格式的。这样服务器在接收到请求时就会知道如何解析请求体中的数据。
当使用org.springframework.web.client.RestTemplate发送HTTP请求并希望修改Content-Type时,您可以使用exchange方法。以下是一个示例,演示了如何使用exchange方法来发送具有不同Content-Type的HTTP请求:
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
public class MyRestClient {
private RestTemplate restTemplate = new RestTemplate();
public void sendRequestWithDifferentContentType() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON); // 设置Content-Type为JSON
String jsonBody = "{\"key\": \"value\"}";
HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);
// 发送POST请求并获取响应
ResponseEntity<String> response = restTemplate.exchange(
"http://example.com/api/endpoint",
HttpMethod.POST,
requestEntity,
String.class
);
// 处理响应
HttpStatus statusCode = response.getStatusCode();
String responseBody = response.getBody();
// 进行进一步的处理...
}
}