添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
代码中加入RestTemplate的配置类
创建RestClientConfig
类,设置连接池大小、超时时间、重试机制等。配置如下:
@Configuration
public class RestClientConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(clientHttpRequestFactory());
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
return restTemplate;
}
@Bean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
try {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build();
httpClientBuilder.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory).build();// 注册http和https请求
// 开始设置连接池
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
poolingHttpClientConnectionManager.setMaxTotal(500); // 最大连接数500
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100); // 同路由并发数100
httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); // 重试次数
HttpClient httpClient = httpClientBuilder.build();
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); // httpClient连接配置
clientHttpRequestFactory.setConnectTimeout(20000); // 连接超时
clientHttpRequestFactory.setReadTimeout(30000); // 数据读取超时时间
clientHttpRequestFactory.setConnectionRequestTimeout(20000); // 连接不够用的等待时间
return clientHttpRequestFactory;
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
log.error("初始化HTTP连接池出错", e);
}
return null;
}
}
发送GET请求
// 1-getForObject()
String response = restTemplate.getForObject(url , String.class);
System.out.println(response);
// 2-getForEntity()
ResponseEntity<String> responseEntity1 = restTemplate.getForEntity(url, String.class);
HttpStatus statusCode = responseEntity1.getStatusCode();
HttpHeaders header = responseEntity1.getHeaders();
String response2 = responseEntity1.getBody();
System.out.println(response2);
// 3-exchange()
RequestEntity requestEntity = RequestEntity.get(new URI(url)).build();
ResponseEntity<String> responseEntity2 = restTemplate.exchange(requestEntity, String.class);
String response3 = responseEntity2.getBody();
System.out.println(response3);
发送POST请求
// 1-postForObject()
User user1 = this.restTemplate.postForObject(uri, user, User.class);
// 2-postForEntity()
ResponseEntity<User> responseEntity1 = this.restTemplate.postForEntity(uri, user, User.class);
// 3-exchange()
RequestEntity<User> requestEntity = RequestEntity.post(new URI(uri)).body(user);
ResponseEntity<User> responseEntity2 = this.restTemplate.exchange(requestEntity, User.class);
设置HTTP Header
// 1-Content-Type
RequestEntity<User> requestEntity = RequestEntity
.post(new URI(uri))
.contentType(MediaType.APPLICATION_JSON)
.body(user);
// 2-Accept
RequestEntity<User> requestEntity = RequestEntity
.post(new URI(uri))
.accept(MediaType.APPLICATION_JSON)
.body(user);
// 3-Other
RequestEntity<User> requestEntity = RequestEntity
.post(new URI(uri))
.header("Authorization", "Basic " + base64Credentials)
.body(user);
发送文件
@RequestMapping(value="/sendFile")
public String sendFile() throws URISyntaxException, IOException {
MultiValueMap<String, Object> multiPartBody = new LinkedMultiValueMap<>();
multiPartBody.add("file", new ClassPathResource("tmp/user.txt"));
RequestEntity<MultiValueMap<String, Object>> requestEntity = RequestEntity
.post(new URI("http://127.0.0.1:8080/upload1"))
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(multiPartBody);
ResponseEntity<String> response = restTemplate.exchange(requestEntity, String.class);
return "sueecess";
}
下载文件
/**
* 下载文件
* @param response
* @throws URISyntaxException
* @throws IOException
*/
@RequestMapping(value="/receiveFile")
public void receiveFile(HttpServletResponse response) throws URISyntaxException, IOException {
// 小文件
RequestEntity requestEntity = RequestEntity.get(
new URI("http://127.0.0.1:8080/downLoad.html")).build();
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(requestEntity, byte[].class);
byte[] downloadContent = responseEntity.getBody();
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"myframe.html\"");
response.addHeader("Content-Length", "" + downloadContent.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(downloadContent, response.getOutputStream());
}
/**
* 大文件
* @param response
* @return
* @throws URISyntaxException
*/
@RequestMapping(value="/bigFile")
public String bigFile(HttpServletResponse response) throws URISyntaxException {
//大文件
ResponseExtractor<ResponseEntity<File>> responseExtractor =
new ResponseExtractor<ResponseEntity<File>>() {
@Override
public ResponseEntity<File> extractData(ClientHttpResponse response)
throws IOException {
File rcvFile = File.createTempFile("rcvFile", "zip");
FileCopyUtils.copy(response.getBody(), new FileOutputStream(rcvFile));
return ResponseEntity.status(response.getStatusCode()).
headers(response.getHeaders()).body(rcvFile);
}
};
RequestCallback requestCallback = new RequestCallback() {
@Override
public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
}
};
ResponseEntity<File> fileBody = this.restTemplate.execute(
new URI("http://127.0.0.1:8080/downLoad.html"),
HttpMethod.GET, requestCallback, responseExtractor);
File file = fileBody.getBody();
file.renameTo(new File("D:/Users/big.hmtl"));
return "success";
}