Springboot's restTemplate configuration and use
In springboot project, you can directly inject RestTemplate to use, or you can use it for simple configuration
Basic configuration
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { return new RestTemplate(factory); } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); (150000); // ms (150000); // ms return factory; } }
The following are advanced configuration and usage
1 Scene
In Java development, use http connection to accessThird-party network interface
, the commonly used connection tool isHttpClient
andOKHttp
。
These two connection tools are more usefulcomplex
, novices are prone to problems. If you use spring framework, you can userestTemplate
To make http connection request.
The default connection method of restTemplate is in javaHttpConnection
, can be usedClientHttpRequestFactory
Specify different HTTP connection methods.
2 Dependencies
Maven depends as follows:
<dependency> <groupId></groupId> <artifactId>spring-web</artifactId> <version>5.2.</version> </dependency> <dependency> <groupId></groupId> <artifactId>httpclient</artifactId> <version>4.5.7</version> </dependency>
3 Configuration
import ; import ; import ; import ; import ; import ; import ; import ; import ; @Configuration public class RestTemplateConfig { /** * http connection manager * @return */ @Bean public HttpClientConnectionManager poolingHttpClientConnectionManager() { /*// Register http and https requests Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", ()) .register("https", ()) .build(); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);*/ PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); // Maximum number of connections (500); // Number of concurrency in the same route (concurrency of each host) (100); return poolingHttpClientConnectionManager; } /** * HttpClient * @param poolingHttpClientConnectionManager * @return */ @Bean public HttpClient httpClient(HttpClientConnectionManager poolingHttpClientConnectionManager) { HttpClientBuilder httpClientBuilder = (); // Set up http connection manager (poolingHttpClientConnectionManager); /*// Set the number of retry (new DefaultHttpRequestRetryHandler(3, true));*/ // Set the default request header /*List<Header> headers = new ArrayList<>(); (new BasicHeader("Connection", "Keep-Alive")); (headers);*/ return (); } /** * Request connection pool configuration * @param httpClient * @return */ @Bean public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) { HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); // httpClient creator (httpClient); // Connection timeout/milliseconds (the time to connect to the server (handshake success) is exceeded, the connection timeout is thrown) (5 * 1000); // Data read timeout (socketTimeout)/ms (the time when the server returns data (response), exceeds the thrown read timeout) (10 * 1000); // The timeout time of the connection pool to obtain the requested connection should not be too long. It must be set /ms (the available connection is not obtained during the timeout, and it will throw: Timeout waiting for connection from pool) (10 * 1000); return clientHttpRequestFactory; } /** * rest template * @return */ @Bean public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) { // Can be created in boot RestTemplate restTemplate = new RestTemplate(); //Configuration request factory (clientHttpRequestFactory); return restTemplate; } }
4 Use
The entity classes used are as follows:
@Data @ToString public class TempUser implements Serializable { private String userName; private Integer age; }
4.1 GET request
Background interface code:
@RequestMapping("getUser") public TempUser getUser(TempUser form) { TempUser tempUser = new TempUser(); (()); (()); return tempUser; }
4.1.1 Normal access
TempUser result = ("http://localhost:8080/cs-admin/rest/getUser?userName=Zhang San&amp;age=18", );
4.1.2 Return HTTP status
ResponseEntity<TempUser> responseEntity = ("http://localhost:8080/cs-admin/rest/getUser?userName=Zhang San&age=18", );// Get the status objectHttpStatus httpStatus = (); // Get the status codeint statusCodeValue = (); // Get headersHttpHeaders httpHeaders = (); // Get bodyTempUser result = ();
4.1.3 Mapping request parameters
Map<String, Object> paramMap = new HashMap<>(); ("userName", "Zhang San"); ("age", 18); TempUser result = ("http://localhost:8080/cs-admin/rest/getUser?userName={userName}&age={age}", , paramMap);
4.2 POST request
4.2.1 Normal access
Background interface code:
RequestMapping("getPostUser") public TempUser getPostUser(@RequestBody TempUser form) { TempUser tempUser = new TempUser(); (()); (()); return tempUser; }
(1) Normal access interface
TempUser param = new TempUser(); ("Zhang San"); (18); TempUser result = ("http://localhost:8080/cs-admin/rest/getPostUser", param, );
(2) With HEAD access interface
// Request header informationHttpHeaders headers = new HttpHeaders(); (("application/json;charset=UTF-8")); //("headParam1", "headParamValue"); // Request contentTempUser param = new TempUser(); ("Zhang San"); (18); // Assembly request informationHttpEntity<TempUser> httpEntity=new HttpEntity<>(param,headers); TempUser result = ("http://localhost:8080/cs-admin/rest/getPostUser", httpEntity, );
4.2.2 Access without request body
Only method is post, the parameter transfer method is still the param method of get
Background interface code:
@RequestMapping("getPostUserNoBody") public TempUser getPostUserNoBody(TempUser form) { TempUser tempUser = new TempUser(); (()); (()); return tempUser; }
Access method:
Map<String, Object> paramMap = new HashMap<>(); ("userName", "Zhang San"); ("age", 18); TempUser result = ("http://localhost:8080/cs-admin/rest/getPostUserNoBody?userName={userName}&age={age}", null, , paramMap); (result);
4.2.3 Send a request to carry files
public static void main(String[] args) { final RestTemplate restTemplate = new RestTemplate(); MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); ("fileUuid","()"); ("sourceLanguageAbbreviation","en"); ("targetLanguageAbbreviation","zh"); HttpHeaders headers = new HttpHeaders(); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers); final ResponseEntity<String> stringResponseEntity = ("http://localhost:8055/documentTrans/updateLanguages", map, ); (stringResponseEntity); }
4.3 Upload files
Background interface code:
@RequestMapping("uploadFile") public TempUser uploadFile(HttpServletRequest request, TempUser form) { MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; //Get file information MultipartFile multipartFile = ("file"); TempUser tempUser = new TempUser(); if (multipartFile != null) { (()+" "+()); } if(form!=null){ (()); } return tempUser; }
Access method:
// documentFileSystemResource file=new FileSystemResource("D:\\Elasticsearch authoritative guide (Chinese version).pdf"); // Set request contentMultiValueMap<String, Object> param=new LinkedMultiValueMap<>(); ("file", file); // Other parameters("userName", "Zhang San"); ("age", 18); // Assembly request informationHttpEntity<MultiValueMap<String, Object>> httpEntity=new HttpEntity<>(param); // Send a requestTempUser result = ("http://localhost:8080/cs-admin/rest/uploadFile", httpEntity, );
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.