Android 的网络编程(6)-天气预报的WebService简单例子

一、获取并使用KSOAP包

在Android SDK中并没有提供调用WebService的库,因此,需要使用第三方的SDK来调用WebService。PC版本的WebService库非常丰富,但这些对Android来说过于庞大。适合手机的WebService客户端的SDK有一些,比较常用的是KSOAP2。

KSOAP2 地址:http://code.google.com/p/ksoap2-android/

我下载的最新的是: ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar

注意:

我在使用ksoap2-android时犯了一个低级错误:使用时报错误:The import org.ksoap2 cannot be resolved。 
当时分析这个问题时一直以为是Eclipse出了问题,找了好多方法都不行, 
实际是我下载的ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar文件是错误的导致的,走了弯路。

在 http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2 页面 通过鼠标右键链接另存为存的是同名的一个纯文本的Html文件。而不是我们想要的。

我是在 
http://code.google.com/p/ksoap2-android/source/browse/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/2.5.4/ksoap2-android-assembly-2.5.4-jar-with-dependencies.jar  点 View raw file 才正确下载对应文件的。

image

 

选择我们的项目,右键菜单中 Build Path –> Add External Archives… 增加这个下载的包

image

增加好后,我们在 选择我们的项目,右键菜单中 Build Path –> Configure Build Path 的 Libraries 中可以看到下面图:

image

二,分以下几步来调用 WebService

 

1、指定 WebService 的命名空间和调用方法

import org.ksoap2.serialization.SoapObject;
private static final String NAMESPACE = "http://WebXml.com.cn/";
private static final String METHOD_NAME = "getWeatherbyCityName";

SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);

SoapObject类的第一个参数表示WebService的命名空间,可以从WSDL文档中找到WebService的命名空间。 
第二个参数表示要调用的WebService方法名。

2、设置调用方法的参数值,如果没有参数,可以省略,设置方法的参数值的代码如下:

rpc.addProperty("theCityName", "北京");

要注意的是,addProperty方法的第1个参数虽然表示调用方法的参数名,但该参数值并不一定与服务端的WebService类中的方法参数名一致,只要设置参数的顺序一致即可。

3、生成调用Webservice方法的SOAP请求信息。

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = rpc;
envelope.dotNet = true;
envelope.setOutputSoapObject(rpc);

创建SoapSerializationEnvelope对象时需要通过SoapSerializationEnvelope类的构造方法设置SOAP协议的版本号。 
该版本号需要根据服务端WebService的版本号设置。 
在创建SoapSerializationEnvelope对象后,不要忘了设置SOAPSoapSerializationEnvelope类的bodyOut属性, 
该属性的值就是在第一步创建的SoapObject对象。

4、创建HttpTransportsSE对象。

这里不要使用 AndroidHttpTransport ht = new AndroidHttpTransport(URL); 这是一个要过期的类

private static String URL = "http://www.webxml.com.cn/webservices/weatherwebservice.asmx";
HttpTransportSE ht = new HttpTransportSE(URL); 
ht.debug = true;

5、使用call方法调用WebService方法

private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";
ht.call(SOAP_ACTION, envelope);

网上有人说这里的call的第一个参数为null,但是经过我的测试,null是不行的。 
第2个参数就是在第3步创建的SoapSerializationEnvelope对象。

6、获得WebService方法的返回结果

有两种方法:

1、使用getResponse方法获得返回数据。

private SoapObject detail;
detail =(SoapObject) envelope.getResponse();

2、使用 bodyIn 及 getProperty。

private SoapObject detail;
SoapObject result = (SoapObject)envelope.bodyIn;
detail = (SoapObject) result.getProperty("getWeatherbyCityNameResult");

7、 这时候执行会出错,提示没有权限访问网络

需要修改 AndroidManifest.xml 文件,赋予相应权限

简单来说就是增加下面这行配置:<uses-permission android:name="android.permission.INTERNET"></uses-permission>

完整的 AndroidManifest.xml 文件 如下:

 

注:Android 中在代码中为了调试写了system.out.print()输出项

在菜单:Window-->show view-->other-->找到Android,选择Logcat 是可以看到输出的, 
如果你想在一个单独的窗口看到system.out.print()的输出的话,可以在logcat界面点那个绿色的“+”好,

在Filter name 和 By log tag里面均填入System.out,这样的话你就能在单独的界面查看system.out.print()的输出了!!

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="ghj1976.MyWeather" android:versionCode="1"
	android:versionName="1.0">

	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<activity android:name=".MyWeatherActivity" android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	</application>
	<uses-permission android:name="android.permission.INTERNET"></uses-permission>

</manifest>

完整的代码如下:

package ghj1976.MyWeather;

import java.io.UnsupportedEncodingException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

public class MyWeatherActivity extends Activity {

	private Button okButton;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		okButton = (Button) this.findViewById(R.id.btn_Search);
		okButton.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				  String city = "北京";
				  getWeather(city);  
			}

		});
	}

	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";

	private static String SOAP_ACTION = "http://WebXml.com.cn/getWeatherbyCityName";

	private String weatherToday;

	private SoapObject detail;

	public void getWeather(String cityName) {
		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);

			
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.bodyOut = rpc;
			envelope.dotNet = true;
			envelope.setOutputSoapObject(rpc);
			
			HttpTransportSE ht = new HttpTransportSE(URL);

			//AndroidHttpTransport ht = new AndroidHttpTransport(URL);
			ht.debug = true;

			ht.call(SOAP_ACTION, envelope);
			//ht.call(null, envelope);

			//SoapObject result = (SoapObject)envelope.bodyIn;
			//detail = (SoapObject) result.getProperty("getWeatherbyCityNameResult");

			detail =(SoapObject) envelope.getResponse();
			
			//System.out.println("result" + result);
			System.out.println("detail" + detail);
			Toast.makeText(this, detail.toString(), Toast.LENGTH_LONG).show();
			parseWeather(detail);

			return;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	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);
		Toast.makeText(this, weatherToday, Toast.LENGTH_LONG).show();

	}
}

参考资料

在Android中访问WebService接口 
http://www.cnblogs.com/yy-7years/archive/2011/01/24/1943286.html

Android调用WebService 
http://express.ruanko.com/ruanko-express_34/technologyexchange5.html

中国气象局的WebService地址 
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx

Android与服务器端数据交互(基于SOAP协议整合android+webservice) 
http://www.cnblogs.com/zhangdongzi/archive/2011/04/19/2020688.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
实验报告封面 课程名称: Android平台开发与应用 课程代码: SM3004 任课老师: 梁郁君 实验指导老师: 梁郁君 实验报告名称:实验10 Android数据存储与IO 学生姓名: 学号: 教学班: 递交日期: 签收人: 我申明,本报告内的实验已按要求完成,报告完全是由我个人完成,并没有抄袭行 为。我已经保留了这份实验报告的副本。 申明人(签名): 实验报告评语与评分: 评阅老师签名: 一、实验名称:Android数据存储与IO 二、实验日期:2014/11/13 三、实验目的: 1、掌握SharedPreferences的存储数据的格式及位置,能够读写其他应用程序的Shared Preferences。 2、File存储数据 3、掌握SQLite存储数据方法。 4、会使用SQLiteOpenHelper辅助类,进行操作数据库。 四、实验用的仪器和材料: PC+Eclipse+ADT 五、实验的步骤和方法: 1、读写其他应用程序SharedPreferences。 读写其他应用程序的SharedPreferences,步骤如下: 创建应用App1 和应用App2,App2尝试读取App1的SharedPreferences内容 在App2 需要创建App1对应的Context。 调用App1的Context的getSharedPreferences(String name,int mode) 即可获取相应的SharedPreferences对象。 如果需要向App1的SharedPreferences数据写入数据,调用SharedPreferences的e dit()方法获取相应的Editor即可。 根据上述说明和下面截图,以及代码注释,完成相关代码片段填空,并思考问题: SharedPreferences何时会丢失? 图1 App1运行的界面 图2 App2 运行结果 App1:记录应用程序的使用次数,/com.Test/UseCount.java程序如下,补充程序中所缺 代码: "import android.app.Activity; " "import android.content.SharedPreferences; " "import android.content.SharedPreferences.Editor; " "import android.os.Bundle; " "import android.widget.Toast; " "public class UseCount extends Activity{ " "SharedPreferences preferences; " "@Override " "public void onCreate(Bundle savedInstanceState){ " "super.onCreate(savedInstanceState); " "setContentView(R.layout.main); " "preferences = getSharedPreferences("count", MODE_WORLD_READABLE); " "//读取SharedPreferences里的count数据 " "int count = ("count" , 0); " "//显示程序以前使用的次数 " "Toast.makeText(this , "程序以前被使用了" + count + "次。", " "10000).show(); " "Editor editor = ; " "//存入数据 " "editor.putInt("count" , ++count); " "//提交修改 " "editor. ; " "} " "} " App2:ReadOtherPreferences.java代码如下,补充程序所缺代码: "import android.app.Activity; " "import android.content.Context; " "import android.content.SharedPreferences; " "import " "android.content.pm.PackageManager.NameNotFoundException; " "import android.os.Bundle; " "import android.widget.TextView; " "public class ReadOtherPreferences extends Activity{ " "Context useCount; " "@Override " "public void onCreate(Bundle sav

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值