package com.example.ksoap2demo;import java.io.UnsupportedEncodingException;import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObject;import org.ksoap2.serialization.SoapSerializationEnvelope;import org.ksoap2.transport.HttpTransportSE;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity { private Button okButton; // 命名空间 private static final String NAMESPACE = "http://WebXml.com.cn/"; // WebService地址 private static String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx"; // 方法 private static final String METHOD_NAME = "getWeatherbyCityName"; /** * SOAPAction: "http://WebXml.com.cn/getWeatherbyCityName" */ private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName"; private String weatherToday; private SoapObject detail; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 查询按钮 okButton = (Button) this.findViewById(R.id.btn_Search); okButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub String city = "北京"; getWeather(city); } }); } public void getWeather(final String cityName) { new Thread(new Runnable() { public void run() { try { System.out.println("rpc------"); SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME); System.out.println("rpc..." + rpc); System.out.println("cityName is... " + cityName); rpc.addProperty("theCityName", cityName); /** * 生成调用Webservice方法的SOAP请求信息 * * 创建SoapSerializationEnvelope对象时需要通过SoapSerializationEnvelope类的构造方法设置SOAP协议的版本号 * 。 该版本号需要根据服务端WebService的版本号设置。 * 在创建SoapSerializationEnvelope对象后 * ,不要忘了设置SOAPSoapSerializationEnvelope类的bodyOut属性, * 该属性的值就是在第一步创建的SoapObject对象。 */ SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.bodyOut = rpc; envelope.dotNet = true; envelope.setOutputSoapObject(rpc); HttpTransportSE ht = new HttpTransportSE(URL); ht.debug = true; ht.call(SOAP_ACTION, envelope); detail = (SoapObject) envelope.getResponse(); parseWeather(detail); return; } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void parseWeather(SoapObject detail) throws UnsupportedEncodingException { String date = detail.getProperty(6).toString(); weatherToday = "今天:" + date.split(" ")[0]; weatherToday = weatherToday + "\n天气:" + date.split(" ")[1]; weatherToday = weatherToday + "\n气温:" + detail.getProperty(5).toString(); weatherToday = weatherToday + "\n风力:" + detail.getProperty(7).toString() + "\n"; System.out.println("weatherToday is " + weatherToday); getWindow().getDecorView().post(new Runnable() { public void run() { Toast.makeText(getWindow().getDecorView().getContext(), weatherToday, Toast.LENGTH_LONG).show(); } }); }}
JAR包下载: