RestTemplate发送请求、基本spring自带RestTemplate发送请求、RestTemplate设置请求头

2023-12-13 10:23:08

今天分享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/json
    HttpHeaders 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);

文章来源:https://blog.csdn.net/my_futrue/article/details/134835284
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。