首页 > 代码库 > Axis2 调用Webservice 接口

Axis2 调用Webservice 接口

1,先学会部署环境,搭建Axis2环境。 http://blog.csdn.net/lanqibaoer/article/details/22731291

现在调用一个现有的公共webservice接口,http://fy.webxml.com.cn/webservices/EnglishChinese.asmx?op=TranslatorString

调用方法:

 TranslatorString  输入中文,翻译成 拼音、英文。
参数:wordKey(中文)


现在要做,翻译词:【随便】,代码如下:

package cn.com.webxml;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

public class Test {
	public static void main(String[] args) throws AxisFault {
			RPCServiceClient serviceClient = new RPCServiceClient();
			Options options = new Options();
			
			options.setAction("http://WebXml.com.cn/TranslatorString"); //因为soap1.2规范必须指定action
			EndpointReference targetEPR  = new EndpointReference("http://fy.webxml.com.cn/webservices/EnglishChinese.asmx?WSDL");
			options.setTo(targetEPR);
			options.setTimeOutInMilliSeconds(6000000000L);//设置超时时间
			options.setTransportInProtocol(Constants.TRANSPORT_HTTP); //传输协议
			serviceClient.setOptions(options);
			 OMFactory fac = OMAbstractFactory.getOMFactory();
		     OMNamespace omNs = fac.createOMNamespace(
		                "http://WebXml.com.cn/","");
		     OMElement method = fac.createOMElement("TranslatorString ", omNs);
		     OMElement wordKey = fac.createOMElement("wordKey",omNs);
		     wordKey.setText("随便");
		     method.addChild(wordKey);
		     method.build();
		     OMElement result = serviceClient.sendReceive(method);
		     System.out.println(getResults(result));
		     System.exit(0);
	}
	/***
	 * 解析XML,将获取到的数据封装到list中
	 * @param element
	 * @return
	 */
	public static List<String> getResults(OMElement element) {
			if (element == null) {
				return null;
			}
			Iterator iterator = element.getChildElements();
			Iterator innerItr;
			List<String> list = new ArrayList<String>();
			OMElement result = null;
			while (iterator.hasNext()) {
				result = (OMElement) iterator.next();
				innerItr = result.getChildElements();
				while(innerItr.hasNext()){
					OMElement result2 = (OMElement)innerItr.next();
					  if(result2!=null){
						  String text = result2.getText();
						  if(text!=null && !("").equals(text)){
							  list.add(text);
						  }
					  }
				}
			}
			return list;
		}
}
运行结果:

注意: