目前常用的跨应用跨平台之间的数据交互,通常采用webapi接口,双方约定请求地址、请求方式、请求参数、响应数据格式、传输数据的加解密方式等进行数据交互,目前做项目遇到一个上游数据提供方提供的接口是webservice的方式以soap协议进行数据交互,这个使用Java的库类封装了一个基于soap协议调用webservice请求返回数据的工具类,记录以作备忘。
导入依赖
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<!--nutz 使用了其中的 base64的工具类,可替换为其他base64的工具类-->
<dependency>
<groupId>org.nutz</groupId>
<artifactId>nutz</artifactId>
<version>1.r.67</version>
</dependency>
封装工具类
import org.apache.http.HttpEntity;
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.nutz.repo.Base64;
import java.nio.charset.StandardCharsets;
/**
* soap 协议发送webservice请求
*
* @author aaa
* @date 2022/3/24 10:05
*/
public class WebServicePostSoapUtils {
/**
* 使用SOAP1.1发送消息
*
* @param postUrl webservice的URL
* @param username Authorization 验证的用户名(根据webservice接口的验证规则决定是否添加)
* @param password Authorization 验证的密码(根据webservice接口的验证规则决定是否添加)
* @param soapXml 请求参数
* @param soapAction 默认为空字符串
* @return
*/
public static String doPostSoap(String postUrl, String username, String password, String soapXml, String soapAction) {
String retStr = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(postUrl);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000)
.setConnectTimeout(6000).build();
httpPost.setConfig(requestConfig);
try {
httpPost.setHeader("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), false));
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction", soapAction);
StringEntity data = new StringEntity(soapXml, StandardCharsets.UTF_8);
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印响应内容
retStr = EntityUtils.toString(httpEntity, "UTF-8");
// System.out.println("response:" + retStr);
}
// 释放资源
closeableHttpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
return retStr;
}
}