Java中以字符串调用SOAP Web服务的最简实现及JUnit测试方案
Got it,这种不想折腾生成一堆SOAP客户端类、只想快速用现有SoapUI请求验证服务的需求,我太懂了!下面给你两种超简便的实现方式,完全满足你要的「快速搭JUnit测试、直接用XML调用」的要求:
方法一:用Java原生HttpURLConnection(无额外依赖)
这种方式不需要引入任何第三方库,纯原生Java就能搞定,适合快速验证。核心就是把你从SoapUI拿到的URL和SOAP信封,直接通过POST请求发出去:
步骤&代码示例
import org.junit.Test; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class SoapIntegrationTest { @Test public void testSoapService() throws Exception { // 替换成你从SoapUI复制的服务端点URL String soapServiceUrl = "https://your-target-soap-service.com/endpoint"; // 替换成你从SoapUI导出的完整SOAP信封(Java 15+支持文本块,低版本请转义双引号) String soapEnvelope = """ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:demo="http://demo.service.com/"> <soapenv:Header/> <soapenv:Body> <demo:GetUserInfo> <demo:userId>12345</demo:userId> </demo:GetUserInfo> </soapenv:Body> </soapenv:Envelope> """; // 建立HTTP连接 URL url = new URL(soapServiceUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // 设置SOAP服务要求的请求头 connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); // 注意:SOAPAction头要从SoapUI的请求头里复制,很多服务依赖它识别操作;如果没有就注释掉 connection.setRequestProperty("SOAPAction", "http://demo.service.com/GetUserInfo"); // 允许写入请求体 connection.setDoOutput(true); try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(soapEnvelope.getBytes("UTF-8")); outputStream.flush(); } // 读取并打印响应 try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) { StringBuilder responseBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { responseBuilder.append(line); } String soapResponse = responseBuilder.toString(); System.out.println("SOAP服务响应:\n" + soapResponse); // 这里可以加断言验证响应,比如检查是否包含预期结果 // assert soapResponse.contains("<demo:userName>JohnDoe</demo:userName>"); } finally { connection.disconnect(); } } }
注意事项
- 如果你的Java版本低于15,把SOAP信封的文本块换成常规字符串,记得把双引号转义成
\" SOAPAction头非常关键:如果SoapUI的请求里有这个头,一定要原样复制;如果没有,直接删除这个请求头设置即可
方法二:用Apache HttpClient(更简洁的流处理)
如果你的项目已经引入了Apache HttpClient,或者觉得原生API写起来繁琐,用这个更省心。它帮你封装了很多流处理和连接管理的细节:
先加Maven依赖(测试范围)
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.14</version> <!-- 可以用最新稳定版 --> <scope>test</scope> </dependency>
JUnit测试代码
import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; 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.junit.Test; public class SoapHttpClientTest { @Test public void testSoapServiceWithHttpClient() throws Exception { String soapServiceUrl = "https://your-target-soap-service.com/endpoint"; String soapEnvelope = """ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:demo="http://demo.service.com/"> <soapenv:Header/> <soapenv:Body> <demo:GetUserInfo> <demo:userId>12345</demo:userId> </demo:GetUserInfo> </soapenv:Body> </soapenv:Envelope> """; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost postRequest = new HttpPost(soapServiceUrl); // 设置请求头 postRequest.setHeader("Content-Type", "text/xml;charset=UTF-8"); postRequest.setHeader("SOAPAction", "http://demo.service.com/GetUserInfo"); // 设置请求体 StringEntity requestEntity = new StringEntity(soapEnvelope, "UTF-8"); postRequest.setEntity(requestEntity); // 发送请求并获取响应 try (CloseableHttpResponse response = httpClient.execute(postRequest)) { HttpEntity responseEntity = response.getEntity(); String soapResponse = EntityUtils.toString(responseEntity, "UTF-8"); System.out.println("SOAP服务响应:\n" + soapResponse); // 断言验证逻辑 // assert soapResponse.contains("<demo:success>true</demo:success>"); } } } }
核心优势总结
这两种方式都完美符合你的需求:
- 完全不需要生成任何SOAP客户端类、JAXB映射对象,直接复用SoapUI里的原始XML
- 代码极简,适合快速排查问题、编写集成测试验证服务可用性
- 如果需要处理安全认证(比如Basic Auth),直接在请求头里添加
Authorization字段即可,非常灵活
内容的提问来源于stack exchange,提问作者WishIWasJeeping
相关产品推荐
相关产品推荐

