Play 2.6:URL参数编码问题
如何将嵌套URL编码为合法格式?
当然有办法啦!你需要对嵌套在父URL里的子URL部分(也就是http://www.bla.com/?contenId=123&User=test这一段)进行URL编码——把那些会干扰URL解析的特殊字符(比如:、/、?、&、=)转换成对应的百分号编码格式。下面给你几种实用的实现方式:
方法1:用浏览器控制台快速搞定(临时场景首选)
打开任意浏览器的开发者工具(按F12,切换到Console标签),直接运行JavaScript的编码函数:
encodeURIComponent("http://www.bla.com/?contenId=123&User=test")
执行后会立刻返回编码后的字符串:http%3A%2F%2Fwww.bla.com%2F%3FcontenId%3D123%26User%3Dtest,把它替换到原URL的对应位置,就能得到你想要的合法URL了。
方法2:Python代码实现(后端/脚本场景)
用Python自带的urllib.parse模块的quote函数,记得指定safe=''参数,确保所有特殊字符都被编码:
from urllib.parse import quote # 待编码的子URL original_sub_url = "http://www.bla.com/?contenId=123&User=test" # 全量编码所有特殊字符 encoded_sub_url = quote(original_sub_url, safe='') # 拼接成完整合法URL full_valid_url = f"http://www.123.com/api/link/{encoded_sub_url}" print(full_valid_url)
运行这段代码后,输出的就是你需要的目标URL。
方法3:JavaScript代码实现(前端/Node.js场景)
不管是浏览器前端还是Node.js环境,都可以用encodeURIComponent函数完成编码:
const originalSubUrl = "http://www.bla.com/?contenId=123&User=test"; const encodedSubUrl = encodeURIComponent(originalSubUrl); const fullValidUrl = `http://www.123.com/api/link/${encodedSubUrl}`; console.log(fullValidUrl);
小提醒
别用encodeURI()代替encodeURIComponent()哦!前者不会编码?、&这些在URL参数里的关键字符,会导致URL解析出错,一定要用encodeURIComponent()或者对应语言里能全量编码特殊字符的函数。
内容的提问来源于stack exchange,提问作者mohamedali10
相关产品推荐
相关产品推荐

