> 技术文档 > HTTP请求组件,http网络请求工具类

HTTP请求组件,http网络请求工具类

package com.pantech.manager.component;import com.pantech.manager.config.XaesbPlatformConfig;import org.springframework.http.*;import org.springframework.web.client.RestTemplate;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.ObjectMapper;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import java.util.Map;import java.util.Optional;/** * 总线系统HTTP请求组件 */@Slf4j@Componentpublic class EsbHttpComponent { @Autowired private XaesbPlatformConfig xaesbPlatformConfig; @Autowired private RestTemplate restTemplate; @Autowired private ObjectMapper objectMapper; // 新增:直接返回复杂类型(如List<Map>) public  Optional sendGetForSuccessBody(String path, TypeReference typeReference) { return sendGetForSuccessBody(path, null, typeReference); } // 新增:带参数的复杂类型返回 public  Optional sendGetForSuccessBody(String path, Map params, TypeReference typeReference) { try { // 先获取字符串响应 Optional responseBody = sendGetForSuccessBody(path, params, String.class); if (responseBody.isPresent()) { // 直接解析为目标复杂类型 T result = objectMapper.readValue(responseBody.get(), typeReference); return Optional.of(result); } } catch (JsonProcessingException e) { log.error(\"复杂类型JSON解析失败\", e); } return Optional.empty(); } /** * 发送GET请求并返回成功的响应体(自动判断200状态和非空内容) */ public  Optional sendGetForSuccessBody(String path, Class responseType) { return sendGetForSuccessBody(path, null, responseType); } /** * 发送带参数的GET请求并返回成功的响应体(自动判断200状态和非空内容) */ public  Optional sendGetForSuccessBody(String path, Map params, Class responseType) { try { ResponseEntity response = sendGetRequest(path, params, responseType); if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) { return Optional.of(response.getBody()); } log.warn(\"GET请求未返回有效内容,状态码: {}\", response.getStatusCode()); } catch (Exception e) { log.error(\"GET请求处理异常\", e); } return Optional.empty(); } /** * 发送POST请求并返回成功的响应体(自动判断200状态和非空内容) */ public  Optional sendPostForSuccessBody(String path, Object requestBody, Class responseType) { try { ResponseEntity response = sendPostRequest(path, requestBody, responseType); if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) { return Optional.of(response.getBody()); } log.warn(\"POST请求未返回有效内容,状态码: {}\", response.getStatusCode()); } catch (Exception e) { log.error(\"POST请求处理异常\", e); } return Optional.empty(); } /** * 发送POST请求并返回成功的复杂类型响应体 */ public  Optional sendPostForSuccessBody(String path, Object requestBody, TypeReference typeReference) { try { ResponseEntity response = sendPostRequest(path, requestBody, String.class); if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) { T result = objectMapper.readValue(response.getBody(), typeReference); return Optional.of(result); } log.warn(\"POST请求未返回有效内容,状态码: {}\", response.getStatusCode()); } catch (JsonProcessingException e) { log.error(\"JSON解析异常\", e); } catch (Exception e) { log.error(\"POST请求处理异常\", e); } return Optional.empty(); } /** * 发送GET请求到总线系统 */ public  ResponseEntity sendGetRequest(String path, Class responseType) { return sendGetRequest(path, null, responseType); } /** * 发送GET请求到总线系统(带参数) */ public  ResponseEntity sendGetRequest(String path, Map params, Class responseType) { try { String apiUrl = buildApiUrl(path); HttpHeaders headers = buildHeaders(); if (params != null && !params.isEmpty()) { apiUrl = appendParamsToUrl(apiUrl, params); } HttpEntity requestEntity = new HttpEntity(headers); log.info(\"发送GET请求: {}\", apiUrl); return restTemplate.exchange(  apiUrl,  HttpMethod.GET,  requestEntity,  responseType ); } catch (Exception e) { log.error(\"GET请求异常: {}\", e.getMessage(), e); throw new RuntimeException(\"发送GET请求失败\", e); } } /** * 发送POST请求到总线系统 */ public  ResponseEntity sendPostRequest(String path, Object requestBody, Class responseType) { try { String apiUrl = buildApiUrl(path); HttpHeaders headers = buildHeaders(); HttpEntity requestEntity = new HttpEntity(requestBody, headers); log.info(\"发送POST请求: {}\", apiUrl); return restTemplate.exchange(  apiUrl,  HttpMethod.POST,  requestEntity,  responseType ); } catch (Exception e) { log.error(\"POST请求异常: {}\", e.getMessage(), e); throw new RuntimeException(\"发送POST请求失败\", e); } } /** * 构建完整的API URL */ private String buildApiUrl(String path) { return xaesbPlatformConfig.getGateway() + xaesbPlatformConfig.getBaseUri() + path; } /** * 构建通用请求头 */ private HttpHeaders buildHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set(xaesbPlatformConfig.getHeader(), xaesbPlatformConfig.getToken() + \"-\" + System.currentTimeMillis()); return headers; } /** * 向URL添加查询参数 */ private String appendParamsToUrl(String url, Map params) { StringBuilder urlBuilder = new StringBuilder(url); boolean isFirstParam = !url.contains(\"?\"); for (Map.Entry entry : params.entrySet()) { if (entry.getValue() != null) { urlBuilder.append(isFirstParam ? \"?\" : \"&\") .append(entry.getKey()) .append(\"=\") .append(entry.getValue().toString()); isFirstParam = false; } } return urlBuilder.toString(); }}

使用示例

/** * 拉取数据 */@PostMapping(\"/pullData\")@ApiOperationSupport(order = 8)@Operation(summary = \"拉取数据\", description = \"拉取数据\")public R pullData() {// 1. 调用工具类发送GET请求,直接获取解析后的List<Map>Optional<List<Map>> dataList = esbHttpComponent.sendGetForSuccessBody(EVENT_NAME, // 接口路径(工具类会自动拼接完整URL)new TypeReference<List<Map>>() {} // 指定返回的复杂类型);// 2. 检查响应是否有效(非业务逻辑,仅流程判断)if (!dataList.isPresent()) {log.warn(\"拉取数据失败,未获取到有效数据,路径: {}\", EVENT_NAME);return R.status(false);}// 3. 核心业务逻辑:转换数据并保存List entities = convertToEntities(dataList.get());dataFimsAircraftRegistrationService.saveBatch(entities);log.info(\"数据拉取成功,共保存 {} 条记录\", entities.size());return R.status(true);}
@Override public OnlineCarHailingResponse sendOnlineCarHailingRequest(OnlineCarHailingRequest request) { // 1. 通过组件发送POST请求,直接获取解析后的响应体 Optional responseBody = esbHttpComponent.sendPostForSuccessBody( ONLINE_CAR_HAILING_API_URI, // 接口路径,组件自动拼接完整URL request,// 请求体对象 OnlineCarHailingResponse.class // 响应体类型 ); // 2. 处理成功响应(200状态且响应体非空) if (responseBody.isPresent()) { return responseBody.get(); } // 3. 处理失败场景(包含:非200状态、响应体空、请求异常等) OnlineCarHailingResponse errorResponse = new OnlineCarHailingResponse(); errorResponse.setCode(1); errorResponse.setMsg(\"接口调用失败或响应无效\"); return errorResponse; }

对于简单的返回类型 用 

public  Optional sendPostForSuccessBody(String path, Object requestBody, Class responseType)

对于复杂的返回类型 比如你自定义的  用 

public  Optional sendPostForSuccessBody(String path, Object requestBody, TypeReference typeReference) {

隔音材料