撒旦
package com.example.day2_getweather;
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 在主线程中不能有访问网页的操作
new Thread() {
@Override
public void run() {
getWeather();
}
}.start();
}
/**
* 联网获得天气的方法
*
* 这里需要导包, SOAP 肥皂 (Simple Object Access Protocol)协议
* soap协议只是用来封装消息用的。封装后的消息你可以通过各种已有的协议来传输 SOAP协议= HTTP协议+ XML数据格式
* SOAP协议是基于HTTP协议的,两者的关系就好比高速公路是基于普通公路改造的,在一条公路上加上隔离栏后就成了高速公路 assembly 装配集合
* dependencies 依赖,相关,管理
* ksoap2-android-assembly-2.5.4-jar-with-dependencies这个包可以使用WebService
*/
private void getWeather() {
// ///
// Web Services Description Language 可能是资源定位的时候说明了地址,也说明了语言类型
// HttpTransportSE httpTransportSE = new HttpTransportSE(url);里用,网页里是wsdl
String url = "http://web.36wu.com/WeatherService.asmx?WSDL";
// SoapObject soapObject = new SoapObject(namespace, name);
String namespace = "http://www.36wu.com/";//这个是为什么首页的地址?
String name = "GetWeather";// 调用方法的名字
// 这个是httpTransportSE.call(soapAction, soapSerializationEnvelope)用的,网页上找不到在哪里
String soapAction = "http://www.36wu.com/GetWeather";
// ///
// 得到对象,同时设置uri(全球资源定位符)地址,这个对象可以 访问地址和得到访问后返回的内容
HttpTransportSE httpTransportSE = new HttpTransportSE(url);
// 获得可以携带与服务器通信的(遵守soap协议)对象, SoapSerializationEnvelope,同时指定是哪一个版本的
SoapSerializationEnvelope soapSerializationEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// 获得封装发送给服务器信息的类,封装发送给服务器的信息(key value模式)
SoapObject soapObject = new SoapObject(namespace, name);
soapObject.addProperty("district", "太原");// 地区
soapObject.addProperty("authkey", "5ae00c9c22fa435ba56161ef0d263b7c");// 申请码
// 设置传递给服务器的信息 把soapObject赋予soapSerializationEnvelope的属性bodyOut上
soapSerializationEnvelope.bodyOut = soapObject;
// 设置对。net语言更好的支持
soapSerializationEnvelope.dotNet = true;
//开始用httpTransportSE对象访问服务器获得东西
try {// 两个参数,第一个是 ??,第二个是封装信息的类
httpTransportSE.call(soapAction, soapSerializationEnvelope);
//得到服务器返回的信息 返回的信息还是在soapSerializationEnvelope中,属性bodyIn取出来后还是soapObject类型
SoapObject bodyIn = (SoapObject) soapSerializationEnvelope.bodyIn;
System.out.println("整体信息是:"+bodyIn.toString());
// 分割第一层
SoapObject bodyIn1 = (SoapObject) bodyIn.getProperty("GetWeatherResult");
System.out.println("getWeatherResult的信息是:"+bodyIn1.toString());
// 获得第二层 key是data的值
SoapObject bodyIn2 = (SoapObject) bodyIn1.getProperty("data");
System.out.println("data的值是:"+bodyIn2.toString());
// 获得key值是minTemp的存在
Object property = bodyIn2.getProperty("minTemp");
System.out.println("minTemp的值是:"+property+"度");
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}