Toy 3: Invoking Live Search Web Service
继续造玩具。本来不想写微软的这个鸡肋型的 Live 搜索引擎的,不过看在它位列三公很久的份上,也写写吧。正如同微软产品中普遍存在过多冗余代码的状况一样,它老人家提供的这个基于 SOAP 的 Web Service 也很多冗余嵌套,一层一层又一层无甚必要的封装,就怕用户不晕菜。更小心眼的是,它居然只提供支持 .NET 的 SDK 、开发文档和样例,其他的开发技术似乎都难入 M$ 的法眼啊。
不过在查询次数限制方面,微软的每天10000次与 Google 的1000次、 Yahoo 的5000次相比就慷慨多了。
玩法一:Generating Web Service Client
就是 wsdl2java 。除了命令行的方式,很多开发工具也提供这种生成功能,比如 Eclipse, NetBeans 都有这方面的支援能力。以下我使用的 Eclipse 3.2.2 + WTP 1.5.3,其内置的 SOAP 实现是 Axis v1.3,共生成了17个 .java 文件。
| public SourceResponse[] search(String query, int start) throws ServiceException, RemoteException { String[] flags = new String[]{"None"}; String[] resultFields = new String[]{"All"}; SourceRequest sreq = new SourceRequest( SourceType.Web, start, 10, null, null, resultFields, null); SearchRequest request = new SearchRequest("your_msn_appid", query, "en-US", SafeSearchOptions.Off, flags, null, new SourceRequest[]{sreq}); MSNSearchService mss = new MSNSearchServiceLocator(); |
从每个 SourceResponse 中再取出一个 Result[] ,轮循就可以了。
玩法二:Dynamic Client
微软的开发者网站上没有提供相关的请求样式和返回结果集样式,或许是我没有找到,不过没关系,我截取了:
Live SOAP Request Envelope
Live SOAP Response Envelope
需要说明的是:在 request 中只有 AppID, Query, CultureInfo, Source 是必须的,其他都是可选项,具体可以参考微软为 .NET SDK 写的文档。
以下代码片断使用 Axis2 v1.1.1 编写。
| public OMElement search(String query, int start) throws AxisFault { String epr = "http://soap.search.msn.com/webservices.asmx"; Options options = new Options(); ServiceClient client = new ServiceClient(); OMElement eSearchRequest = fac.createOMElement("Request", ns, root); OMElement eAppID = fac.createOMElement("AppID", ns, eSearchRequest); OMElement eRequests = fac.createOMElement("Requests", ns, eSearchRequest); OMElement eSourceRequest = fac.createOMElement("SourceRequest", ns, eRequests); OMElement eOffset = fac.createOMElement("Offset", ns, eSourceRequest); return client.sendReceive(root); |
按照上面提供的返回样式分析包含有结果集的 XML 片断即可。