springboot3.1 使用restTemplate httpclient5 fastjson 配置
时间: 2024-06-08 19:05:40 浏览: 402
springboot实现FastJson解析json数据的方法
5星 · 资源好评率100%
首先,需要在 `pom.xml` 文件中添加以下依赖:
```xml
<dependencies>
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Test Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Apache HttpClient 5 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient5</artifactId>
<version>5.1.2</version>
</dependency>
<!-- Fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
</dependencies>
```
然后,创建一个 `RestTemplate` 的 Bean:
```java
import org.apache.hc.client5.http.async.methods.SimpleHttpRequests;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.Method;
import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsAsyncClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.Future;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
restTemplate.setInterceptors(Collections.singletonList(new RestTemplateHeaderModifierInterceptor(headers)));
// 设置请求和响应的消息转换器
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN));
restTemplate.setMessageConverters(Collections.singletonList(converter));
// 设置请求工厂
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000);
requestFactory.setReadTimeout(10000);
restTemplate.setRequestFactory(requestFactory);
return restTemplate;
}
@Bean
public AsyncRestTemplate asyncRestTemplate() {
AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
asyncRestTemplate.setInterceptors(Collections.singletonList(new RestTemplateHeaderModifierInterceptor(headers)));
// 设置请求和响应的消息转换器
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN));
asyncRestTemplate.setMessageConverters(Collections.singletonList(converter));
// 设置请求工厂
HttpComponentsAsyncClientHttpRequestFactory requestFactory = new HttpComponentsAsyncClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000);
requestFactory.setReadTimeout(10000);
asyncRestTemplate.setAsyncRequestFactory(requestFactory);
return asyncRestTemplate;
}
private static class RestTemplateHeaderModifierInterceptor implements org.springframework.http.client.ClientHttpRequestInterceptor {
private final HttpHeaders headers;
public RestTemplateHeaderModifierInterceptor(HttpHeaders headers) {
this.headers = headers;
}
@Override
public org.springframework.http.client.ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
headers.forEach((key, value) -> request.getHeaders().put(key, value));
return execution.execute(request, body);
}
}
}
```
其中,`RestTemplateHeaderModifierInterceptor` 是用来设置请求头的拦截器,`MappingJackson2HttpMessageConverter` 是用来转换请求和响应消息的消息转换器,`HttpComponentsClientHttpRequestFactory` 和 `HttpComponentsAsyncClientHttpRequestFactory` 是用来配置请求工厂的。
在上面的代码中,我同时定义了同步和异步的 `RestTemplate`,你可以根据需要选择其中一个。
使用示例:
```java
import com.alibaba.fastjson.JSONObject;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/test")
public class TestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/sync")
@ResponseBody
public String testSync() {
String url = "https://jsonplaceholder.typicode.com/todos/1";
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
return responseEntity.getBody();
}
@GetMapping("/async")
@ResponseBody
public String testAsync() throws Exception {
String url = "https://jsonplaceholder.typicode.com/todos/1";
Future<ResponseEntity<String>> future = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
ResponseEntity<String> responseEntity = future.get();
return responseEntity.getBody();
}
}
```
上面的示例中,我使用 `RestTemplate` 发送了一个 GET 请求,请求的 URL 是 `https://jsonplaceholder.typicode.com/todos/1`,并且指定了响应消息的类型为 `String`。如果你需要发送 POST 请求,只需要将 `HttpMethod.GET` 改为 `HttpMethod.POST`,并且设置请求体即可。
阅读全文