Python中XML请求含&符号的URL被截断问题求助
解决URL在x-www-form-urlencoded请求中被&截断的问题
问题原因
你手动拼接application/x-www-form-urlencoded格式的payload时,URL里的&符号会被当作请求参数的分隔符,导致后端仅识别到&之前的部分,后续内容被误解析为新的请求参数,而非目标URL的组成部分。
解决方案
方案1:用字典传递data(推荐)
无需手动处理编码,requests会自动对所有参数值完成URL编码,彻底避免拼接错误:
payload = { "data[Product][pro_STOCK_CODE]": product_no, "data[Product][pro_NAME]": name, "data[Product][cat_ID]": ids, "data[Image][0]": image # 直接传入完整URL即可 } headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'} response2 = requests.request("POST", url2, headers=headers, data=payload)
方案2:手动编码URL后拼接
如果坚持手动拼接payload,需用urllib.parse.quote对包含特殊字符的URL单独编码:
from urllib.parse import quote # 对存储完整URL的image变量进行编码 encoded_image_url = quote(image) payload = (f"data[Product][pro_STOCK_CODE]={product_no}&&data[Product][pro_NAME]={name}&&" f"data[Product][cat_ID]={ids}&&data[Image][0]={encoded_image_url}") headers = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'} response2 = requests.request("POST", url2, headers=headers, data=payload.encode('utf8'))
补充说明
application/x-www-form-urlencoded格式要求参数值中的特殊字符(如&、=、%)必须经过URL编码,否则会破坏参数结构。使用字典传递data是最稳妥的方式,能避免手动拼接时的编码遗漏或错误。
内容的提问来源于stack exchange,提问作者Mehmet Akif Demir
相关产品推荐
相关产品推荐

