最近在论坛内看到好多与webservice有关的问题。恰好今天下午有点时间,就写一篇文章大概介绍下。由于类型比较多,这里介绍比较常用的wsdl类型的。基础知识就不再介绍。
当然,访问一个webservice可能方法很多,这里我主要介绍两种。
访问中央电视台节目的。
webservice接口地址是:http://webservice.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx
wsdl路径是:http://webservice.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx?wsdl
一般地方告诉你webservice接口地址,在后面加上?wsdl即为wsdl地址。
一、soap方式。
这里并不是严格意义上的纯soap访问。
加上头,以及请求的部分,代码如下,就不多介绍了。自己对照图片看,很好理解。
String address = "http://webservice.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx"; URL url = new URL(address); HttpURLConnection http = (HttpURLConnection) url.openConnection(); http.setDoOutput(true); http.setDoInput(true); http.setRequestMethod("POST"); http.setUseCaches(false); http.setRequestProperty("Content-Type","text/xml"); http.connect(); DataOutputStream out = new DataOutputStream(http.getoutputStream()); String cityId = "-4"; String content = "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\"><soap12:Body><getTvstationDataSet xmlns=\"http://WebXml.com.cn/\"><theAreaID>" + cityId + "</theAreaID></getTvstationDataSet></soap12:Body></soap12:Envelope>"; out.writeBytes(content); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(http .getInputStream())); String line; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); http.disconnect(); System.out.println(buffer.toString());
返回结果自己就随便处理了。
二、axis方式访问。
准备好wsdl2java,这里不推荐工具,建议下载axis1工具包,里面有wsdl2java类。
public static void main(String[] args) { String[] s = new String[] { "-u","http://webservice.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx?wsdl","-o","client","-S","false","-t" }; WSDL2Java.main(s); }-u是wsdl地址,-o是输出目录,别的自己搜索。
运行后生成如下包
复制根目录cn到src下。
能使用的就是stub结尾的java类,可能不止一个,随便用一个就行了。我一般用12stub。
public static void main(String[] args) throws Exception { ChinaTVprogramWebServiceSoap12Stub tv = new ChinaTVprogramWebServiceSoap12Stub( new URL( "http://webservice.webxml.com.cn/webservices/ChinaTVprogramWebService.asmx?op=getTvstationDataSet"),null); GetTvstationDataSetResponseGetTvstationDataSetResult ss = tv .getTvstationDataSet(-1); MessageElement[] ms = ss.get_any(); System.out.println(ms[1]); for (MessageElement s : ms) { System.out.println(s.toString()); } }
参数里的URL地址,是你要访问的节点的url,比如要访问第一个图里的getTvstationDataSet功能,点击他,进入一个页面,复制地址栏的地址就行了。
运行就是你想要的结过了。
以上只是简单的介绍一下,webservice其实很简单。多使用几个就行了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。