当前位置: 首页 > news >正文

JAVA原生实现SOAP POST调用

1. 场景

最近客户给了一个 API,如图,最开始以为是一个传统的post请求,结果始终返回一段奇怪的响应。
在这里插入图片描述
最后和小伙伴沟通、查阅资料后才知道是一种特有的SOAP协议的请求方式。

2. 原生java

豆包和Deepseek 给了一种非原生的方式,需要安装依赖和执行wsimport命令行命令。
这里提供一种清爽的方法,代码如下:

2.1 SOAP client实现
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;@Log4j2
@Service
public class WeatherSoapClient {private static final String SOAP_ENDPOINT = "http://12.122.222.223:7777/GetSeaWeather.asmx?op=GetCurSeaWeatherInfo";// 根据实际文档设置命名空间private static final String SOAP_NAMESPACE = "http://tempuri.org/";public Map<String, Object> getWeatherData(double longitude, double latitude) {try {// 1. 构建 SOAP 请求体String soapRequest = buildSoapRequest(longitude, latitude);log.info("SOAP Request: {}", soapRequest);// 2. 发送 POST 请求String soapResponse = sendSoapRequest(soapRequest);// 3. 解析 SOAP 响应String str = extractTagContent(soapResponse, "GetCurSeaWeatherInfoResult");JSONObject jsonObject = JSON.parseObject(str, JSONObject.class);return jsonObject;} catch (Exception e) {throw new RuntimeException("SOAP request failed", e);}}private String buildSoapRequest(double lon, double lat) {return String.format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +"<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\"" +"               xmlns:api=\"%s\">" +"   <soap:Header/>" +"   <soap:Body>" +"       <api:GetCurSeaWeatherInfo>" +"           <api:lon>%s</api:lon>" +"           <api:lat>%s</api:lat>" +"       </api:GetCurSeaWeatherInfo>" +"   </soap:Body>" +"</soap:Envelope>",SOAP_NAMESPACE, lon, lat);}private String sendSoapRequest(String soapRequest) throws Exception {try (CloseableHttpClient httpClient = HttpClients.createDefault()) {HttpPost httpPost = new HttpPost(SOAP_ENDPOINT);// 设置 SOAP 特定请求头httpPost.setHeader("Content-Type", "text/xml; charset=utf-8");httpPost.setHeader("SOAPAction", SOAP_NAMESPACE + "GetCurSeaWeatherInfo");// 设置请求体httpPost.setEntity(new StringEntity(soapRequest, ContentType.TEXT_XML));try (CloseableHttpResponse response = httpClient.execute(httpPost)) {HttpEntity entity = response.getEntity();if (entity == null) {throw new RuntimeException("Empty response from SOAP service");}// 获取响应内容String responseContent = EntityUtils.toString(entity);EntityUtils.consume(entity);// 检查 HTTP 状态码int statusCode = response.getStatusLine().getStatusCode();if (statusCode != 200) {throw new RuntimeException("SOAP service returned HTTP " + statusCode +"\nResponse: " + responseContent);}return responseContent;}}}public static String extractTagContent(String xmlStr, String tagName) {String pattern = "<" + tagName + ">(.*?)</" + tagName + ">";Pattern r = Pattern.compile(pattern, Pattern.DOTALL);Matcher m = r.matcher(xmlStr);if (m.find()) {return m.group(1);}return null;}}
2.2 controller
    @Autowiredprivate WeatherSoapClient weatherSoapClient;@GetMapping("/getCurrentWeather")public ApiResult getCurrentWeather(@RequestParam double lon,@RequestParam double lat) {try {Map<String, Object> weatherData = weatherSoapClient.getWeatherData(lon, lat);return ApiResult.ok(weatherData);} catch (Exception e) {Map<String, Object> error = new HashMap<>();error.put("error", "SOAP request failed");error.put("message", e.getMessage());return ApiResult.fail(ApiCode.BUSINESS_EXCEPTION, error);}}
http://www.dtcms.com/a/284844.html

相关文章:

  • 【深度学习】神经网络过拟合与欠拟合-part5
  • 尚庭公寓----------分页查询
  • 外贸ERP软件有哪些?八大热门erp软件功能测评
  • FOC算法中SIMULINK一些常用模块(3)自动计算电机参数
  • OpenBayes 一周速览丨字节EX-4D上线,实现单目视频到自由视角生成;GLM-4.1V-9B-Thinking开源,10B参数比肩Qwen系列
  • JPA 与 MyBatis-Plus 数据库自增主键实现方案
  • TDengine 的可视化数据库操作工具 taosExplorer(安装包自带)
  • 从虚拟大脑到世界行者:具身智能与机器人控制基础
  • python qam
  • Jmeter 性能测试响应时间过长怎么办?
  • 使用 NVIDIA Triton推理服务器的好处
  • 嵌入式学习-PyTorch(6)-day23
  • CCLink IE转ModbusTCP网关配置无纸记录器(上篇)
  • 小程序按住说话
  • zlmediakit接入Onvif设备方案
  • The Missing Semester of Your CS Education 学习笔记以及一些拓展知识(二)
  • 嵌入式基础 -- ADC(模数转换器,Analog to Digital Converter)
  • 疯狂星期四文案网第10天运营日报
  • Kotlin自定义排序
  • AUTOSAR进阶图解==>AUTOSAR_SWS_EFXLibrary
  • Lotus-基于大模型的查询引擎 -开源学习整理
  • 打印文件/打印机队列 - 华为OD机试真题(Java 题解)
  • QT 交叉编译环境下,嵌入式设备显示字体大小和QT Creator 桌面显示不一致问题解决
  • 中国力学大会倒计时2天●千眼狼科学仪器在实验力学研究中应用
  • 状态机(State Machine)是什么?
  • 【秋招ready】
  • 网络初级安全第二次作业
  • css样式中的选择器和盒子模型
  • JoditEditor编辑与预览模式
  • 电碳表:精准计量每一度电的碳排放