"""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())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/android-tutorial-webservice-lab/explore-tutorial-webservice.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-webservice.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1972.zip