一、WebService接口正常使用SOAP协议调用,测试时常采用SoapUI软件调用,具体如下:
二、由于目前主流web服务逐渐转换为RESTful的形式,且SOAP协议的实现也是基于HTTP协议,故存在通过HTTP调用WebService接口的可能
2.1 打开对应的WebService地址,目的地址location即为HTTP REST方式需要调用的服务地址
2.2 在HTTP REST 请求头中添加SOAPAction字段
SOAPAction 可以提供关于 SOAP 消息中要调用的具体操作或方法的信息。这对于接收方来说是非常重要的,因为它帮助确定如何解析和处理收到的 SOAP 消息
如果在发起 SOAP 请求时未在 SOAPAction 中提供有效的操作或方法信息,请求接收方可能会根据其他信息(例如消息体中的内容)来确定应该执行的操作,或者可能会采取默认行为来处理请求
此时SOAPAction可设置为空或者WSDL中对应的Operation(PACSreturn)
2.3 Body内容为xml格式,内容即为SoapUI调用时传输的全部内容
三、代码实现
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Objects;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
@Service
public class PostSoap {
// 请求超时时间
static int socketTimeout = 10000;
// 传输超时时间
static int connectTimeout = 10000;
public static String doPostSoap(String code, String message) {
// 服务地址
String webServiceURL = "http://10.146.8.226/csp/hsb/DHC.Published.PUB0007.BS.PUB0007.cls";
// 拼接报文
String soapXml =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org\">\n"
+ " <soapenv:Header/>\n"
+ " <soapenv:Body>\n"
+ " <tem:PACSreturn>\n"
+ " <!--Optional:-->\n"
+ " <tem:input1>" + code + "</tem:input1>\n"
+ " <!--Optional:-->\n"
+ " <tem:input2>" + message + "</tem:input2>\n"
+ " </tem:PACSreturn>\n"
+ " </soapenv:Body>\n"
+ "</soapenv:Envelope> ";
// 创建HttpClient
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
// 创建Post请求
HttpPost httpPost = new HttpPost(webServiceURL);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
// 设置Post请求报文头部
httpPost.setHeader("Content-Type", "application/xml");
httpPost.setHeader("SOAPAction", "");
// 添加报文内容
StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
httpPost.setEntity(data);
try {
// 执行请求获取返回报文
CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (Objects.nonNull(httpEntity)) {
// 打印响应内容
System.out.println(EntityUtils.toString(httpEntity, "UTF-8"));
}
// 释放资源
closeableHttpClient.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String code = "接口001";
String message = "报文xml";
doPostSoap(code, message);
}
}
运行结果