目前常用的跨应用跨平台之间的数据交互,通常采用webapi接口,双方约定请求地址、请求方式、请求参数、响应数据格式、传输数据的加解密方式等进行数据交互,目前做项目遇到一个上游数据提供方提供的接口是webservice的方式以soap协议进行数据交互,这个使用Java的库类封装了一个基于soap协议调用webservice请求返回数据的工具类,记录以作备忘。
导入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<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;
public class WebServicePostSoapUtils {
public static String doPostSoap(String postUrl, String username, String password, String soapXml, String soapAction) {
String retStr = "";
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
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");
}
closeableHttpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
return retStr;
}
}
|