WebService 代码

1.第一步去下载ksoap jar包 放在在android工程libs中,之后添加这个jar包

2.在manifest.xml添加 网络访问权限 

之后代码:

package com.example.webservice;

import java.util.Properties;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class WebService {
	//webService的名字空间
	private static final String NAMESPACE="http://WebXml.com.cn/";
	//天气预报 webservice地址
	private static String addr = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";  
	//action  名字空间+webservice方法名
	private static String soapAction = "http://WebXml.com.cn/getWeather";
	//
	private static final String WATHER_METHOD_NAME="getWeather";
	
	public static String getWeather(String cityName){
		//创建 soap对象
		SoapObject rpc=new SoapObject(NAMESPACE,WATHER_METHOD_NAME);
		
		SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
		//结果字符串
		String result="empty";
		//
	    envelope.bodyOut=rpc;
	    //是否是.net webservice
	    envelope.dotNet=true;
	    //输出的soapObject
	    envelope.setOutputSoapObject(rpc);
	    
	    //
	    HttpTransportSE transport=new HttpTransportSE(addr);

		rpc.addProperty("theCityCode",cityName);
		
		try{
			transport.call(soapAction, envelope);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		SoapObject object =(SoapObject)envelope.bodyIn;
		if(object!=null){
			result=object.getProperty(0).toString();
			
		}
          		
		return result;
		
	}
	

}

jar包写好现成的方法了 ,很简单。另外 webservice 也可以以url 形式访问,之后从url中获取返回值 进行xml解析即可  


你可能感兴趣的:(WebService 代码)