Android中调用WebService的实例(KSOAP2 )

  经过两天的学习摸索,终于有点小成果,所以贴出来大家看看。没怎么写过 Java,如果代码中有错误请大家指正。

       我在开发过程中遇到的最棘手的一个问题就是,每次请求数据后返回的数据都是空的。针对这种现象我另起了一个线程专门负责发送请求和接收数据,果然问题解决了,虽然不知道是不是问题的症结所在,但总算有了个结果。废话不多说,直接上代码。

1.布局文件,很简洁,只有一个按钮睡觉

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/query_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</RelativeLayout>
2.程序源码:

package com.example.mywebserviceclient;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;

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

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

	private TextView resultView;
	private Button queryButton;
	private String resultString;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		queryButton = (Button) findViewById(R.id.query_btn);
		
		queryButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				new Thread(runnable).start();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	
	private Handler mHandler = new MyHandler(this);
	//avoid handler leak
	private static class MyHandler extends Handler{
	    private final WeakReference<MainActivity> mActivity;
	    public MyHandler(MainActivity activity) {
	        mActivity = new WeakReference<MainActivity>(activity);
	    }
	    @Override
	    public void handleMessage(Message msg) {
	    	Toast.makeText(mActivity.get(), mActivity.get().resultString, Toast.LENGTH_LONG).show();
	        super.handleMessage(msg);
	    }
	}
	
	Runnable runnable = new Runnable(){
	    @Override
	    public void run() {
	       
	        Message msg = new Message();
	        // 查询信息
			try {
				getRemoteInfo(null);
				MainActivity.this.mHandler.sendMessage(msg);
			} catch (SoapFault e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	};

	public void getRemoteInfo(String phoneSec) throws SoapFault {
		// 命名空间
		String nameSpace = "http://WebXml.com.cn/";
		// 调用的方法名称
		String methodName = "getWeatherbyCityName";
		// EndPoint
		String endPoint = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
		// SOAP Action
		String soapAction = "http://WebXml.com.cn/getWeatherbyCityName";

		// 指定WebService的命名空间和调用的方法名
		SoapObject rpc = new SoapObject(nameSpace, methodName);

		// 设置需调用WebService接口需要传入的两个参数mobileCode、userId
		rpc.addProperty("theCityName", "北京");
		//rpc.addProperty("userId", "");

		// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

		envelope.bodyOut = rpc;
		// 设置是否调用的是dotNet开发的WebService
		envelope.dotNet = true;
		// 等价于envelope.bodyOut = rpc;
		envelope.setOutputSoapObject(rpc);

		HttpTransportSE transport = new HttpTransportSE(endPoint);
		try {
			// 调用WebService
			transport.call(soapAction, envelope);
		} catch (Exception e) {
			e.printStackTrace();
		}

		//transport
		// 获取返回的数据
		SoapObject object = (SoapObject) envelope.getResponse();
		try {
			parseWeather(object);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void parseWeather(SoapObject detail)
			throws UnsupportedEncodingException {
		String date = detail.getProperty(6).toString();
		String weatherToday;
		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);
		resultString = weatherToday;
	}
}

到此完毕,希望对大家有帮助!

注:

1.不要忘记引入ksoap2的Jar包。

2.不要忘记打开网络访问权限,<uses-permission android:name="android.permission.INTERNET"/>。

如果是刚学习webservice推荐大家阅读以下两篇文章;

http://blog.csdn.net/lyq8479/article/details/6420398

http://blog.csdn.net/lyq8479/article/details/6428288

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值