webservice实现有多种方式
比如最常用的有axis框架,xfire框架,通过该框架可以发布wsdl接口,也可以实现webservice客户端,目前eclipse都有集成的插件,可以根据wsdl文件生成webservice客户端调用接口,但是这样部署的时候必须依赖框架的jar包,有时候可能因为环境等等原因,我们仅仅需要wsdl中的某一个接口,这时候可以通过http接口或socket接口直接发生xml数据,来调用服务端webservice服务,其实webservice底层还是发送xml数据,只是框架封装了对xml数据进行序列化与反序列化操作,下面以两个简单的例子说明http方式和socket方式。
http实现webservice接口调用例子:
import Java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class HttpPostTest { void testPost(String urlStr) { try { URL url = new URL(urlStr); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setRequestProperty("Pragma:", "no-cache"); con.setRequestProperty("Cache-Control", "no-cache"); con.setRequestProperty("Content-Type", "text/xml"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); String xmlInfo = getXmlInfo(); out.write(new String(xmlInfo)); out.flush(); out.close(); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = ""; StringBuffer buf = new StringBuffer(); for (line = br.readLine(); line != null; line = br.readLine()) { buf.append(new String(line.getBytes(),"UTF-8")); } System.out.println(buf.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private String getXmlInfo() { // 通过wsdl文件可以查看接口xml格式数据,构造调用接口xml数据 String xml = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + "<SOAP-ENV:Body>" + "<m:getItemDetailSingle xmlns:m=\"http:xxxxxxxxxxxxxxxxxx/\">" + "<itemMo>" + "<category>工厂类</category>" + "<city>北京</city>" + "<flag>1</flag>" + "<itemId>0</itemId>" + "<itemIndex>1</itemIndex>" + "<keyword></keyword>" + "<mobile>2147483647</mobile>" + "<password>123456</password>" + "<userName>sohu</userName>" + "</itemMo>" + "</m:getItemDetailSingle>" + "</SOAP-ENV:Body>" + "</SOAP-ENV:Envelope>"; return xml; } public static void main(String[] args) throws UnsupportedEncodingException { String url = "http://localhost:9003/dataService/services/Job"; new HttpPostTest().testPost(url); } }