WebService是基於Web的服務,WebService使用SOAP協議實現跨編程語言和跨操作系統平台,接收和響應外部系統的某種請求,從而實現遠程調用。WebService采用HTTP協議傳輸數據,采用XML格式封裝數據,SOAP協議=HTTP協議+XML數據格式。主要解決不了不同的系統或者調用分布部署的處理數據項目返回的接口。
最近自己在項目中,調用webService接口常用到兩種方法,自己覺得也比較好用,在這里記錄一下。
第一種,采用httpclient 請求,這種跟我們經常用的HTTP請求一樣,結果可以是返回XML格式的字符串,我們比較容易對其進行解析,取得我們想要的數據。
地址:列如 http://www.xxx.com/WeatherWS/Weather.asmx?wsdl
調用的方法是:GetCityForecastByZIP 方法參數是: ZIP
需要的JAR如下:
commons-codec-1.4.jar
commons-httpclient-3.1.jar
jsoup-1.6.2.jar
commons-logging-1.0.4.jar
代碼:
InputStream is = null; HttpClient client = new HttpClient(); PostMethod method = new PostMethod("www.xxx.com/WeatherWSS/Weather.asmx/GetCityForecastByZIP"); method.setRequestHeader("Host", "www.xxx.com"); method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); method.setParameter("ZIP", "90001"); try { client.executeMethod(method); is = method.getResponseBodyAsStream(); Document document = Jsoup.parse(is,"gbk",""); System.err.println(document); } catch (Exception e) { e.printStackTrace(); }finally{ method.releaseConnection(); try { if(is!=null){ is.close(); } } catch (IOException e) { e.printStackTrace(); } }
我這邊 document 是返回XML格式的形式,可以對進行處理,獲取我們想要的數據。
如圖:
第二種:采用axis2來調用。這種 axis2通用性不好,有的web服務用axis2不好用。
地址:列如 http://www.xxx.com/WeatherWS/Weather.asmx?wsdl
調用的方法是:GetCityForecastByZIP 方法參數是: ZIP
需要的JAR如下:
axis-ant.jar axis.jar commons-discovery-0.2.jar commons-logging-1.0.4.jar jaxrpc.jar wsdl4j-1.5.1.jar
代碼:
try{ // 指出service所在URL String endpoint = "http://www.xxx.com/WeatherWS/Weather.asmx"; String targetNamespace = "http://www.xxx.com/WeatherWS/"; String method="GetCityForecastByZIP"; // 創建一個服務(service)調用(call) Service service = new Service(); Call call = (Call) service.createCall();// 通過service創建call對象 // 設置service所在URL call.setTargetEndpointAddress(new java.net.URL(endpoint)); call.setOperationName(new QName(targetNamespace, method)); call.setUseSOAPAction(true); call.addParameter(new QName(targetNamespace,"ZIP"), org.apache.axis.encoding.XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);//接口的參數 //call.setReturnClass(org.w3c.dom.Element.class); call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);//設置返回類型 //String path = targetNamespace + method; //call.setSOAPActionURI(path); Object ret = call.invoke(new Object[] {"90001"}); System.out.println("xx==="+ret.toString()); }catch(Exception e){ e.printStackTrace(); }
我比較經常使用httpclient 請求。也可以使用WSDL2JAVA把WSDL文件轉為本地的服務類,然后可以直接調用。