最终效果
在网上找了一个免费的webservice接口简单做个测试,可以正常返回结果
public static void main(String[] args) {
String url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
String xmlData = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://WebXml.com.cn/\">\n" +
" <soapenv:Header/>\n" +
" <soapenv:Body>\n" +
" <web:getSupportCity>\n" +
" <!--Optional:-->\n" +
" <web:byProvinceName>江苏</web:byProvinceName>\n" +
" </web:getSupportCity>\n" +
" </soapenv:Body>\n" +
"</soapenv:Envelope>";
callWebservice(null,xmlData,url);
}
intelj控制台执行结果
17:53:38.952 [main] DEBUG org.springframework.web.client.RestTemplate - Reading to [java.lang.String] as “text/xml;charset=utf-8”
result==={“getSupportCityResponse”:{“xmlns”:“http://WebXml.com.cn/”,“getSupportCityResult”:{“string”:[“南京 (58238)”,“苏州 (58357)”,“昆山 (58356)”,“南通 (58259)”,“太仓 (58377)”,“吴县 (58349)”,“徐州 (58027)”,“宜兴 (58346)”,“镇江 (58248)”,“淮安 (58145)”,“常熟 (58352)”,“盐城 (58151)”,“泰州 (58246)”,“无锡 (58354)”,“连云港 (58044)”,“扬州 (58245)”,“常州 (58343)”,“宿迁 (58131)”]}}}
soapui执行结果
核心方法
支持Auth授权、支持本地证书、支持在线证书
public static Map<String, String> callWebservice(String certUrl, String xmlData, String url) {
Map<String, String> resMap = new HashMap<>();
try {
// 用户名和密码 进行Base64编码,如果是不需要账号密码授权,可去掉
// String username = "test";
// String password = "111111";
// String auth = username + ":" + password;
// byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
// String authHeader = "Basic " + new String(encodedAuth);
// 不需要证书直接new
RestTemplate restTemplate = new RestTemplate();
// 使用带证书的restTemplate,可以是在线证书url,也可以是本地证书
// RestTemplate restTemplate = RestUtils.createRestTemplate(KeyStoreUtils.loadKeyStoreFromUrl(certUrl));
// RestTemplate restTemplate = RestUtils.createRestTemplate(KeyStoreUtils.loadKeyStore("D:\\ABC.cer"));
HttpHeaders httpHeaders = new HttpHeaders();
MediaType mediaType = MediaType.parseMediaType("text/xml; charset=UTF-8");
httpHeaders.setContentType(mediaType);
// httpHeaders.add("Authorization", authHeader);
HttpEntity<String> httpEntity = new HttpEntity<>(xmlData, httpHeaders);
ResponseEntity