Java调用WebService接口实践案例

最终效果

在网上找了一个免费的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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值