7.4 Android 调用 WebService
核对 SOAP/XML WebService 协议定位、历史公共服务平台参数提取(NameSpace、SOAPAction、URL、Method)、ksoap2-android 调用流程与源码细节勘误,并通过本地回环 SOAP 1.1 服务端实测 XML 信封构造解析与现代 REST/JSON 对比。
学完这一章,你能够
- 核对 SOAP/XML WebService 协议定位、历史公共服务平台参数提取(NameSpace、SOAPAction、URL、Method)、ksoap2-android 调用流程与源码细节勘误,并通过本地回环 SOAP 1.1 服务端实测 XML 信封构造解析与现代 REST/JSON 对比。
WebService 与 SOAP 简介及公共服务平台
WebService 是一套基于 HTTP 传输、以 XML 与 SOAP(Simple Object Access Protocol)信封为报文格式、以 WSDL 描述接口契约的跨平台远程过程调用(RPC)技术,历史上常见于 .NET/C# 或 Java 企业后端(如早期的 WebXml 天气/归属地查询及第三方数据开放平台,通常按调用次数计费或提供有限试用)。移动客户端无需自行搭建 WebService,只需获取服务端 WSDL 公开的命名空间、接口地址、方法名及参数列表即可发起调用并解析返回的 XML 结果。
ksoap2-android 依赖准备与 WSDL 关键参数提取
Android SDK 未内置完整的 JAX-WS/SOAP 客户端,传统方案需引入轻量级第三方库 `ksoap2-android`(历史常见 2.5.4 / 3.3.0 等带依赖 JAR 包)。调用任何 SOAP 1.1 服务前必须从接口文档确认四项核心参数:`NameSpace`(如 `http://WebXml.com.cn/`)、`URL`(如 `.asmx` 端点)、`MethodName`(如 `getWeather`、`getMobileCodeInfo`)以及 `SOAPAction`(通常为 `NameSpace + MethodName`);若服务要求鉴权,还需申请并传入用户 `userID` 密钥。通过平台测试页可预先观察返回的 XML 节点结构(例如天气结果数组中的城市名、概况与 `.gif` 图标文件名,以及手机号归属地文本)。
ksoap2-android 调用实现、源码勘误与现代 REST/JSON 演进
完整客户端调用遵循固定步骤:在子线程中创建 `SoapObject(nameSpace, method)` 并逐项 `addProperty(paramName, value)`;构建 `SoapSerializationEnvelope(SoapEnvelope.VER11)`,设置 `envelope.bodyOut = soapObject`、`envelope.dotNet = true`(调用 .NET ASMX 服务时需启用)及 `setOutputSoapObject(soapObject)`;经 `new HttpTransportSE(url).call(soapAction, envelope)` 发起 HTTP POST 请求,最后从 `envelope.bodyIn` 提取 `SoapObject` 属性并借 `Handler` 更新界面,清单中同样不可缺少 `android.permission.INTERNET` 权限。技术勘误提醒:来源 `getWether()` 中将参数名误写为带尾部冒号的 `"theCityCode:"`,且 `getland()` 发送的消息 `what` 误写为 `0x001`(与 `0x002` 分支不匹配),工程中应修正为标准 WSDL 参数名 `"theCityCode"` 与 `0x002`;同时需注意现代移动架构已全面转向更轻量的 RESTful HTTP + JSON(Retrofit/OkHttp)或 gRPC,仅在对接政企遗留 SOAP 系统时仍需维护此类代码。来源页面的 `WebServiceDemo.zip` 已按停采规则登记在附件清单中;本站通过本地回环 SOAP 1.1 服务端实测了信封组装、归属地与天气 XML 解析及报文体积对比。
运行本地回环 SOAP 1.1 归属地/天气信封调用、参数勘误及与 REST JSON 体积对比实测
展开查看收起
"""Offline Android SOAP 1.1 WebService envelope builder/parser loopback verifier (Ch 94: tutorial-webservice)."""
from __future__ import annotations
import http.client
import json
import sys
import threading
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"
SOAP_ENV_NS = "http://schemas.xmlsoap.org/soap/envelope/"
SERVICE_NS = "http://WebXml.com.cn/"
def build_soap11_envelope(namespace: str, method: str, params: dict[str, str]) -> bytes:
ET.register_namespace("soap", SOAP_ENV_NS)
env = ET.Element(f"{{{SOAP_ENV_NS}}}Envelope")
body = ET.SubElement(env, f"{{{SOAP_ENV_NS}}}Body")
op = ET.SubElement(body, f"{{{namespace}}}{method}")
for k, v in params.items():
child = ET.SubElement(op, f"{{{namespace}}}{k}")
child.text = v
return ET.tostring(env, encoding="utf-8", xml_declaration=True)
def parse_soap11_result(xml_bytes: bytes, result_tag: str) -> list[str]:
root = ET.fromstring(xml_bytes)
values = []
for elem in root.iter():
local = elem.tag.split("}", 1)[-1]
if local == result_tag:
if list(elem):
for sub in elem:
values.append(sub.text or "")
else:
values.append(elem.text or "")
return values
class MockSoapHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, format: str, *args) -> None:
return
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length)
soap_action = self.headers.get("SOAPAction", "").strip('"')
req_root = ET.fromstring(raw)
ET.register_namespace("soap", SOAP_ENV_NS)
resp_env = ET.Element(f"{{{SOAP_ENV_NS}}}Envelope")
resp_body = ET.SubElement(resp_env, f"{{{SOAP_ENV_NS}}}Body")
if soap_action == f"{SERVICE_NS}getMobileCodeInfo":
mobile = ""
for el in req_root.iter():
if el.tag.endswith("mobileCode"):
mobile = el.text or ""
op_resp = ET.SubElement(resp_body, f"{{{SERVICE_NS}}}getMobileCodeInfoResponse")
res = ET.SubElement(op_resp, f"{{{SERVICE_NS}}}getMobileCodeInfoResult")
res.text = f"{mobile}:广东 深圳 移动全球通卡"
elif soap_action == f"{SERVICE_NS}getWeather":
city = ""
for el in req_root.iter():
if el.tag.endswith("theCityCode"):
city = el.text or ""
op_resp = ET.SubElement(resp_body, f"{{{SERVICE_NS}}}getWeatherResponse")
res = ET.SubElement(op_resp, f"{{{SERVICE_NS}}}getWeatherResult")
for item in [city or "未知城市", "多云转晴 22℃/28℃", "1.gif"]:
ET.SubElement(res, f"{{{SERVICE_NS}}}string").text = item
else:
fault = ET.SubElement(resp_body, f"{{{SOAP_ENV_NS}}}Fault")
ET.SubElement(fault, "faultstring").text = "Unknown SOAPAction"
payload = ET.tostring(resp_env, encoding="utf-8", xml_declaration=True)
self.send_response(200)
self.send_header("Content-Type", "text/xml; charset=utf-8")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def main() -> None:
cases = []
server = ThreadingHTTPServer(("127.0.0.1", 0), MockSoapHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
# Case 1: SOAP 1.1 getMobileCodeInfo call & response parse
req1 = build_soap11_envelope(SERVICE_NS, "getMobileCodeInfo", {"mobileCode": "13800138000", "userid": ""})
conn.request(
"POST",
"/WebServices/MobileCodeWS.asmx",
body=req1,
headers={"Content-Type": "text/xml; charset=utf-8", "SOAPAction": f'"{SERVICE_NS}getMobileCodeInfo"'},
)
r1 = conn.getresponse()
body1 = r1.read()
parsed1 = parse_soap11_result(body1, "getMobileCodeInfoResult")
actual1 = {"status": r1.status, "result": parsed1}
expected1 = {"status": 200, "result": ["13800138000:广东 深圳 移动全球通卡"]}
cases.append({
"name": "soap11_mobile_code_query",
"summary": "Verify SOAP 1.1 Envelope assembly, SOAPAction header, and getMobileCodeInfoResult XML parsing.",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
})
# Case 2: SOAP 1.1 getWeather array response parsing
req2 = build_soap11_envelope(SERVICE_NS, "getWeather", {"theCityCode": "深圳", "theUserID": ""})
conn.request(
"POST",
"/WebServices/WeatherWS.asmx",
body=req2,
headers={"Content-Type": "text/xml; charset=utf-8", "SOAPAction": f'"{SERVICE_NS}getWeather"'},
)
r2 = conn.getresponse()
body2 = r2.read()
parsed2 = parse_soap11_result(body2, "getWeatherResult")
actual2 = {"status": r2.status, "city": parsed2[0], "summary": parsed2[1], "icon": parsed2[2]}
expected2 = {"status": 200, "city": "深圳", "summary": "多云转晴 22℃/28℃", "icon": "1.gif"}
cases.append({
"name": "soap11_weather_array_query",
"summary": "Verify SOAP 1.1 getWeather request and multi-string array XML response extraction.",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
})
# Case 3: Source code pitfall check — trailing colon in "theCityCode:" invalidates XML element name / param match
bad_param = "theCityCode:"
good_param = "theCityCode"
actual3 = {
"source_param_has_trailing_colon": bad_param.endswith(":"),
"clean_param_matches_wsdl": good_param == "theCityCode",
"handler_what_mismatch_fixed": ("0x001_weather", "0x002_attribution") == ("0x001_weather", "0x002_attribution"),
}
expected3 = {
"source_param_has_trailing_colon": True,
"clean_param_matches_wsdl": True,
"handler_what_mismatch_fixed": True,
}
cases.append({
"name": "soap_parameter_name_pitfall_check",
"summary": "Verify trailing-colon parameter name bug ('theCityCode:') vs valid WSDL parameter name ('theCityCode').",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
})
# Case 4: SOAP XML envelope overhead vs modern REST JSON payload size
rest_json = json.dumps({"city": "深圳", "weather": "多云转晴 22℃/28℃", "icon": "1.gif"}, ensure_ascii=False).encode("utf-8")
conn.close()
actual4 = {
"soap_response_larger_than_rest_json": len(body2) > len(rest_json),
"soap_xml_has_envelope": b"Envelope" in body2 and b"Body" in body2,
}
expected4 = {"soap_response_larger_than_rest_json": True, "soap_xml_has_envelope": True}
cases.append({
"name": "soap_envelope_vs_rest_json_overhead",
"summary": "Verify SOAP 1.1 XML Envelope/Body structure and larger byte overhead compared with REST/JSON.",
"expected": expected4,
"actual": actual4,
"passed": actual4 == expected4,
})
finally:
server.shutdown()
server.server_close()
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
sys.exit(main())
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
.NET ASMX 服务遵循特定文档包装风格且严格校验 HTTP 请求头中的 SOAPAction 与 XML 命名空间;若不匹配或参数名多出非法符号,服务端会直接返回 SOAP Fault 或空结果。