java對接webservice接口的4種方式總結(jié)
這兩天一直在做外系統(tǒng)對接,對方的接口是webservice的形式,調(diào)用起來有些蛋疼,于是在這里記錄一下我嘗試過的調(diào)用WebService的三種方式。
方式一:以HttpURLConnection的方式調(diào)用
String url ="http://127.0.0.1/cwbase/Service/hndg/Hello.asmx?wsdl"; URL realURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) realURL.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); connection.setRequestProperty("content-length",String.valueOf(xmlData.length)); connection.setRequestMethod("POST"); DataOutputStream printOut = new DataOutputStream(connection.getOutputStream()); printOut.write(xmlOutString.getBytes("UTF-8"));//xmlOutString是自己拼接的xml,這種方式就是通過xml請求接口 printOut.flush(); printOut.close(); // 從連接的輸入流中取得回執(zhí)信息 InputStream inputStream = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream,"UTF-8"); BufferedReader bufreader = new BufferedReader(isr); String xmlString = ""; int c; while ((c = bufreader.read()) != -1) { xmlString += (char) c; } isr.close(); //處理返回的xml信息 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); //從對方的節(jié)點中取的返回值(節(jié)點名由對方接口指定) String returnState = d.getElementsByTagName("ReturnStatus").item(0).getFirstChild().getNodeValue();
方式二:使用apache-cxf生成java類調(diào)用
下載apache-cxf并配置環(huán)境變量(參照JAVA環(huán)境變量配置),配置成功后cmd輸入wsdl2java -help即可驗證是否成功。
接著在cmd中輸入wsdl2java -encoding utf-8 -d 生成路徑 接口地址,即可在指定路徑生成接口JAVA文件,生成后的JAVA類如下圖:
生成以后調(diào)用起來就很簡單了,例子如下:
String result = ""; NC65To63ProjectService service = new NC65To63ProjectService(); NC65To63ProjectServicePortType servicePort =service. getNC65To63ProjectServiceSOAP11PortHttp(); result = servicePort.receiptProject(json);
方式三:使用AXIS調(diào)用WebService
為了避免找不到對方包,所以我直接把包貼在頂上了。
import org.apache.axis.client.Service; import org.apache.axis.client.Call; import org.apache.axis.encoding.XMLType; import javax.xml.namespace.QName; import javax.xml.rpc.ParameterMode; String result = ""; String url = "http://127.0.0.1/uapws/service/nc65to63projectsysplugin";//這是接口地址,注意去掉.wsdl,否則會報錯 Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress(url); String parametersName = "string";//設置參數(shù)名 call.setOperationName("receiptProject");//設置方法名 call.addParameter(parametersName, XMLType.XSD_STRING, ParameterMode.IN);//方法參數(shù),1參數(shù)名、2參數(shù)類型、3.入?yún)? call.setReturnType(XMLType.XSD_STRING);//返回類型 String str = json; Object resultObject = call.invoke(new Object[] { str });//調(diào)用接口 result = (String) resultObject;
方式四:試用httpclient
public static void main(String args[]) { // 第一種方法 ---------------------------------------------- JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance(); // 創(chuàng)建客戶端連接 Client client = factory.createClient("http://127.0.0.1:8080/xx/service/userOrg?wsdl"); Object[] res = null; try { QName operationName = new QName("http://impl.webservice.userorg.com/","findUser");//如果有命名空間需要加上這個,第一個參數(shù)為命名空間名稱,調(diào)用的方法名稱 res = client.invoke(operationName, "admin");//后面為WebService請求參數(shù)數(shù)組 System.out.println(res[0]); }catch (Exception e) { e.printStackTrace(); } // 第二種方法 ---------------------------------------------- // 被<![CDATA[]]>這個標記所包含的內(nèi)容將表示為純文本 String xmlData = "<![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<accounts>" + "<account>" + "<accId>帳號ID(必填)</accId>" + "<userPasswordMD5>密碼</userPasswordMD5>" + "<userPasswordSHA1>密碼</userPasswordSHA1>" + "其中userPasswordSHA1標簽代表SHA1加密后的密碼,userPasswordMD5標簽代表MD5加密后的密碼" + "<name>姓名</name>" + "<sn>姓</sn>" + "<description>描述 </description>" + "<email>郵箱 </email>" + "<gender>性別</gender>" + "<telephoneNumber>電話號碼</telephoneNumber>" + "<mobile>移動電話</mobile>" + "<startTime>用戶的開始生效時間(YYYY-MM-DD HH:mm:SS)</startTime>" + "<endTime>用戶結(jié)束生效時間(YYYY-MM-DD HH:mm:SS) </endTime>" + "<idCardNumber>身份證號碼</idCardNumber>" + "<employeeNumber>工號 </employeeNumber>" + "<o>用戶所屬的組織的編碼號 </o>" + "<employeeType>用戶類型</employeeType>" + "<supporterCorpName>所在公司名稱 </supporterCorpName>" + "</account>" + "</accounts>]]>"; //調(diào)用方法 String method = "sayHello"; method = "getUserList"; String data="<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://impl.webservice.platform.hotent.com/\">"+ "<soapenv:Body>"+ "<ser:"+method+">"+ "<arg0>"+ xmlData + "</arg0>"+ "</ser:"+method+">"+ "</soapenv:Body>"+ "</soapenv:Envelope>"; String httpUrl="http://127.0.0.1:8080/xx/service/helloWorld?wsdl"; httpUrl="http://127.0.0.1:8080/xx/service/userOrg?wsdl"; try { //第一步:創(chuàng)建服務地址 URL url = new URL(httpUrl); //第二步:打開一個通向服務地址的連接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //第三步:設置參數(shù) //3.1發(fā)送方式設置:POST必須大寫 connection.setRequestMethod("POST"); //3.2設置數(shù)據(jù)格式:content-type connection.setRequestProperty("content-type", "text/xml;charset=utf-8"); //3.3設置輸入輸出,因為默認新創(chuàng)建的connection沒有讀寫權(quán)限, connection.setDoInput(true); connection.setDoOutput(true); //第四步:組織SOAP數(shù)據(jù),發(fā)送請求 String soapXML = data; //將信息以流的方式發(fā)送出去 // DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫到流里面 OutputStream os = connection.getOutputStream(); os.write(soapXML.getBytes()); //第五步:接收服務端響應,打印 int responseCode = connection.getResponseCode(); System.out.println("responseCode: "+responseCode); if(200 == responseCode){//表示服務端響應成功 //獲取當前連接請求返回的數(shù)據(jù)流 InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String temp = null; while(null != (temp = br.readLine())){ sb.append(temp); } is.close(); isr.close(); br.close(); System.out.println(StringEscapeUtils.unescapeXml(sb.toString())); //轉(zhuǎn)義 System.out.println(sb.toString()); } else { //異常信息 InputStream is = connection.getErrorStream(); //通過getErrorStream了解錯誤的詳情,因為錯誤詳情也以XML格式返回,因此也可以用JDOM來獲取。 InputStreamReader isr = new InputStreamReader(is,"utf-8"); BufferedReader in = new BufferedReader(isr); String inputLine; BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("d:\\result.xml")));// 將結(jié)果存放的位置 while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); bw.write(inputLine); bw.newLine(); bw.close(); } in.close(); } os.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } // 把xml轉(zhuǎn)義 public static String escapeXml(String xml) { String newXml = xml.replaceAll("<", "<").replaceAll(">", ">").replaceAll(" ", " ").replaceAll("\"", """); return newXml; }
總結(jié)
第一種使用HttpURLConnection調(diào)用的方法,基本不用擔心什么兼容問題,但是通過xml請求接口,需要自己手動拼接xml(一般通過soapui生成,然后在程序中根據(jù)情況拼接),并且返回的數(shù)據(jù)也是xml,還要通過代碼解析,可以說是極其麻煩了。
第二種apache-cxf生成java類調(diào)用的方式,直接調(diào)用生成的類即可訪問接口,非常方便,但是apache-cxf和jdk有兼容問題,如果關聯(lián)的某個jar包中的代碼有沖突,就會遇到痛苦的報錯了。在我的嘗試中,就有一個Service沖突的問題,網(wǎng)上說需要更改某jar包中的class文件,但是由于項目太過龐大,擔心會觸發(fā)其他的問題,所以我只能就此作罷。
重點來了,第三種AXIS的方式, 沒有啥兼容問題的方式了,調(diào)用起來非常簡便,不需要拼接xml,返回的也只能干凈的數(shù)據(jù),
第四種:
httpclient本人親測好用。不用引用cxf或AXIS一大堆jar包,比較方便
到此這篇關于java對接webservice接口的4種方式總結(jié)的文章就介紹到這了,更多相關java對接webservice接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring MVC Mybatis多數(shù)據(jù)源的使用實例解析
項目需要從其他網(wǎng)站獲取數(shù)據(jù),因為是臨時加的需求,這篇文章主要介紹了Spring MVC Mybatis多數(shù)據(jù)源的使用實例解析,需要的朋友可以參考下2016-12-12SpringBoot security安全認證登錄的實現(xiàn)方法
這篇文章主要介紹了SpringBoot security安全認證登錄的實現(xiàn)方法,也就是使用默認用戶和密碼登錄的操作方法,本文結(jié)合實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2023-02-02解決mybatis-plus3.4.1分頁插件PaginationInterceptor和防止全表更新與刪除插件SqlE
這篇文章給大家介紹了在Spring.xml文件中配置mybatis-plus3.4.1分頁插件PaginationInterceptor和防止全表更新與刪除插件SqlExplainInterceptor過時失效問題解決方案,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2020-12-12Java開發(fā)框架spring實現(xiàn)自定義緩存標簽
這篇文章主要介紹了Java開發(fā)框架spring實現(xiàn)自定義緩存標簽的詳細代碼,感興趣的小伙伴們可以參考一下2015-12-12