网络请求中的URL中传bool型数据

本文介绍在Objective-C中处理URL拼接布尔类型数据的正确方法,避免使用NSString直接转换导致的问题,通过字符串字面量的方式确保布尔值正确表示为'true'或'false'。

如果在URL中要拼接bool的数据,OC这边不能使用BOOL型。因为使用NSString的拼接字符串类方法中,会将BOOL型数据转化为0或者1。
解决办法:
NSString *overdue_string = overdue ? @"true" : @"false";
然后将overdue_string拼接到URL中。

转载于:https://www.cnblogs.com/cchHers/p/8712242.html

#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 可复用/可新建两种模式的 WebSocket 客户端(ws/wss 均可)。 - 复用模式:共用一个长连接,适合频繁调用 - 新建模式:单次调用独立新建连接,避免影响已有会话 """ import asyncio import json import ssl from typing import Optional, Dict, Any import websockets from websockets import WebSocketClientProtocol WS_URL = "ws://10.56.160.130:8001/robot" # 改为你的地址,如 wss://host:port/robot PING_INTERVAL = 20 PING_TIMEOUT = 20 def make_ssl_context(url: str) -> Optional[ssl.SSLContext]: if url.startswith("wss://"): ctx = ssl.create_default_context() # 自签名测试可放开以下两行(生产不要这么做) # ctx.check_hostname = False # ctx.verify_mode = ssl.CERT_NONE return ctx return None class WSClientManager: """ 管理一个可复用的长连接,并提供“复用/新建”两种发送方式。 - reuse=True:复用(若无连接则自动建立) - reuse=False:临时新建连接,用后即关,不影响复用连接 """ _instance = None def __init__(self, url: str): self.url = url self.ssl_ctx = make_ssl_context(url) self._ws: Optional[WebSocketClientProtocol] = None self._lock = asyncio.Lock() self._bound_robot_id: Optional[str] = None @classmethod def instance(cls, url: str = WS_URL) -> "WSClientManager": if cls._instance is None: cls._instance = WSClientManager(url) return cls._instance async def _ensure_connected(self): if self._ws and self._ws.open: return # 重连 if self._ws: try: await self._ws.close() except Exception: pass self._ws = None self._ws = await websockets.connect( self.url, ssl=self.ssl_ctx, ping_interval=PING_INTERVAL, ping_timeout=PING_TIMEOUT, ) async def close(self): async with self._lock: if self._ws: try: await self._ws.close() except Exception: pass self._ws = None self._bound_robot_id = None async def bind_robot(self, robot_id: str, reuse: bool = True): """ 绑定/重绑 robot_id。 - reuse=True:对复用连接操作;如果没连接会自动建立 - reuse=False:对临时连接无意义(可直接在 send 中 robot_id) """ if not reuse: return # 跳过:临时连接在 send 时带 robot_id 即可 async with self._lock: await self._ensure_connected() # 触发一次“带 robot_id”的请求用于绑定 await self._send_locked({"method": "robot-status", "robot_id": robot_id}) self._bound_robot_id = robot_id async def send(self, payload: Dict[str, Any], reuse: bool = True, rebind_if_needed: bool = True) -> Any: """ 发送命令: - reuse=True:复用长连接,自动建连;可选自动重绑 robot_id - reuse=False:新建临时连接,发送并接收一次后关闭 返回:服务端响应(JSON或原始字符串) """ if reuse: async with self._lock: await self._ensure_connected() # 自动重绑(首条或 robot_id 变更) robot_id = payload.get("robot_id") if rebind_if_needed and robot_id and robot_id != self._bound_robot_id: # 先用 robot_id 触发重绑 await self._send_locked({"method": "robot-status", "robot_id": robot_id}) self._bound_robot_id = robot_id # 随后发送真实 payload(可不带 robot_id) payload = {k: v for k, v in payload.items() if k != "robot_id"} return await self._send_locked(payload) else: # 临时连接模式 ws = await websockets.connect( self.url, ssl=self.ssl_ctx, ping_interval=PING_INTERVAL, ping_timeout=PING_TIMEOUT, ) try: await ws.send(json.dumps(payload, ensure_ascii=False)) resp = await ws.recv() try: return json.loads(resp) except Exception: return resp finally: try: await ws.close() except Exception: pass async def _send_locked(self, payload: Dict[str, Any]) -> Any: assert self._ws is not None await self._ws.send(json.dumps(payload, ensure_ascii=False)) resp = await self._ws.recv() try: return json.loads(resp) except Exception: return resp # --------------- 示例:在项目不同位置调用 --------------- async def part_a_use_reuse(robot_id: str): """ 业务 A:复用连接发送多个请求(自动建连、自动重绑) """ client = WSClientManager.instance() # 第一次调用:携带 robot_id,会自动重绑 r1 = await client.send({"method": "robot-status", "robot_id": robot_id}, reuse=True) print("A-1:", r1) # 第二次调用:已绑定可不带 robot_id r2 = await client.send({"method": "ROBOT-MOVE-TO-HOME-REQ"}, reuse=True) print("A-2:", r2) async def part_b_use_new_connection(robot_id: str): """ 业务 B:不干扰复用连接,新建临时连接一次性发送 """ client = WSClientManager.instance() r = await client.send({"method": "robot-status", "robot_id": robot_id}, reuse=False) print("B:", r) async def part_c_switch_robot_id(new_robot_id: str): """ 业务 C:在复用连接上切换 robot_id(重绑) """ client = WSClientManager.instance() await client.bind_robot(new_robot_id, reuse=True) r = await client.send({"method": "robot-status"}, reuse=True) print("C:", r) # --------------- 主函数:按需组合 --------------- async def main(): client = WSClientManager.instance(WS_URL) try: await part_a_use_reuse(robot_id="1") await part_b_use_new_connection(robot_id="2") await part_c_switch_robot_id(new_robot_id="2") # 在任意位置都可以继续复用: r3 = await client.send({"method": "robot-status"}, reuse=True) print("Main:", r3) finally: await client.close() if __name__ == "__main__": asyncio.run(main()) 详细解释一下上述代码,并给出优化意见和优化的完整代码
最新发布
09-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值