今天分享RestTemplate,直接上代码:
因个人需求需要重写RestTemplate,并设置请求头
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
String username = "admin";
String password = "admin123";
@Bean
public RestTemplate restTemplate() {
CloseableHttpClient customHttpClient = returnCloseableHttpClient();
// 使用 HttpComponentsClientHttpRequestFactory 配置 RestTemplate
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(customHttpClient);
RestTemplate restTemplate = new RestTemplate(factory);
// 配置 MappingJackson2HttpMessageConverter 以处理 JSON 数据
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
return restTemplate;
}
public CloseableHttpClient returnCloseableHttpClient(){
// 创建 HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 设置 BasicAuth
CredentialsProvider provider = new BasicCredentialsProvider();
// 创建认证范围
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// 创建凭据对
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
provider.setCredentials(scope, credentials);
httpClientBuilder.setDefaultCredentialsProvider(provider);
// 创建自定义的 CloseableHttpClient
return httpClientBuilder.build();
}
}
----调用前提:
@Service
public class SysEmployeeCardServiceImpl implements SysEmployeeCardService {
@Value("${access-control-address}")
private String ipAddress;
private final RestTemplate restTemplate;
@Autowired
public SysEmployeeCardServiceImpl(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public CardInfoSearch findEmployeeCard(CardInfoSearchCond cardInfoSearchCond) {
String url = ipAddress + Constants.CARDINFO_SEARCH ;
String jsonRequest= JsonUtils.ctreteJsonString("CardInfoSearchCond",cardInfoSearchCond);
String result = JsonUtils.resultString(jsonRequest,url,restTemplate, HttpMethod.POST);
System.out.println(result);
CardInfoSearch cardInfoSearch=parseEmployeeCardFromResult(result);
return cardInfoSearch;
}
}
-----调用:
/**** @param jsonRequest 请求体* @param url 请求url* @param restTemplate* @param httpMethod 请求方式* @return*/ public static String resultString(String jsonRequest, String url, RestTemplate restTemplate,HttpMethod httpMethod){// 创建HTTP请求头,通常需要设置Content-Type为application/jsonHttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<String> requestEntity = new HttpEntity<>(jsonRequest, headers);// 发送POST请求,并获取响应//String result = restTemplate.postForObject(url, requestEntity, String.class);ResponseEntity<String> resultEntity = restTemplate.exchange(url, httpMethod, requestEntity, String.class);String result = resultEntity.getBody();return result; }
--------不需要设置请求的话,直接发送
RestTemplate 直接发送get
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); String responseBody = response.getBody();
RestTemplate 直接发送post
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
HttpEntity<String> entity = new HttpEntity<>("requestBody", headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
String responseBody = response.getBody();
RestTemplate 直接发送put
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");
HttpEntity<String> entity = new HttpEntity<>("requestBody", headers);
ResponseEntity<String> response = restTemplate.put(url, entity, String.class);
String responseBody = response.getBody();
RestTemplate 直接发送delete
ResponseEntity<String> response = restTemplate.delete(url);