1、基於Springboot整合RestTemplate調用Webservice接口,如果感覺使用webservice客戶端調用服務器端不會,或者不方便 的時候,可以嘗試使用RestTemplate來調用Webservice接口。
首先,需要做的就是要獲取到請求webservice服務器端的xml文件,此時,需要根據wsdl生成請求webservice服務器端的xml文件,可以使用SoapUi這個文件來操作,點擊File -> New SOAP Project,來創建一個工程。
然后導入wsdl文件,起個工程名稱,這個時候,導入成功之后,就可以看到要請求的xml格式了。
此時,就可以看到要請求的xml,如果有需要進行驗證的參數封裝到請求頭里面soapenv:Header。
將需要驗證的參數封裝到請求頭里面,如下所示:
2、當你拿到要請求的參數的時候,此時,我想使用resttemplate,還是其他請求http的工具,你都可以進行服務調用的吧,關鍵點,就是你拼裝請求參數,就可以了。
1 @Override 2 public String getXxxRest(UserInfo userInfo) { 3 // 創建一個請求頭對象 4 HttpHeaders headers = new HttpHeaders(); 5 MediaType type = MediaType.parseMediaType("text/xml;charset=UTF-8"); 6 // 設置請求頭對象contentTyp的為text/xml;charset=UTF-8 7 headers.setContentType(type); 8 9 10 String username = userInfo.getUsername(); 11 String password = userInfo.getPassword(); 12 String inputXml = userInfo.getinputXml(); 13 14 // 將請求參數進行封裝並進行遠程接口服務調用 15 // 構造webservice請求參數 16 StringBuffer soapRequestData = new StringBuffer(""); 17 soapRequestData.append( 18 "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.tongtech.com/\">"); 19 soapRequestData.append("<soapenv:Header>"); 20 soapRequestData.append("<tongtechheader>"); 21 soapRequestData.append("<id>"); 22 soapRequestData.append(userInfo.getId()); 23 soapRequestData.append("</id>"); 24 25 soapRequestData.append("<cart>"); 26 soapRequestData.append(userInfo.getCart()); 27 soapRequestData.append("</cart>"); 28 29 soapRequestData.append("</tongtechheader>"); 30 soapRequestData.append("</soapenv:Header>"); 31 32 soapRequestData.append("<soapenv:Body>"); 33 soapRequestData.append("<web:getBirthInfo>"); 34 35 soapRequestData.append("<username>"); 36 soapRequestData.append(username); 37 soapRequestData.append("</username>"); 38 39 soapRequestData.append("<password>"); 40 soapRequestData.append(password); 41 soapRequestData.append("</password>"); 42 43 soapRequestData.append("<inputXml>"); 44 soapRequestData.append(userInfo.getInputXml()); 45 soapRequestData.append("</inputXml>"); 46 47 soapRequestData.append("</web:getBirthInfo>"); 48 soapRequestData.append("</soapenv:Body>"); 49 soapRequestData.append("</soapenv:Envelope>"); 50 51 // 創建請求 52 HttpEntity<String> request = new HttpEntity<String>(soapRequestData + "", headers); 53 54 // 發送post請求並獲取到響應結果 55 String str = null; 56 // 封裝一下返回結果 57 Map<String, Object> analyseResult = new HashMap<String, Object>(); 58 try { 59 str = restTemplate.postForObject(請求地址, request, String.class); 60 logger.info("-----------Response content-----------: " + str); 61 } catch (RestClientException e) { 62 e.printStackTrace(); 63 } 64 65 return str; 66 }
雖然你可以使用Webservice客戶端來調用服務器端,但是如果實在不想那樣搞,也可以通過resttemplate或者其他http請求方式進行接口i調用的。