使用 API 网关时出现 Unicode 转换问题

Unicode conversion issue while using API gateway

以下 URL 按预期工作并且 returns "null".

https://zga2tn1wgd.execute-api.us-east-1.amazonaws.com/mycall?url=https://mr.wikipedia.org/s/4jp4

但是同一个页面,使用 unicode 字符串而不是 ascii 字符串,抛出错误:

"errorMessage": "'ascii' codec can't encode characters in position 10-20: ordinal not in range(128)", "errorType": "UnicodeEncodeError"

如何在将字符串传递到 API 网关时对 unicode 字符进行编码?

https://zga2tn1wgd.execute-api.us-east-1.amazonaws.com/mycall?url=https://mr.wikipedia.org/wiki/%E0%A4%95%E0%A4%BF%E0%A4%B6%E0%A5%8B%E0%A4%B0%E0%A4%BE%E0%A4%B5%E0%A4%B8%E0%A5%8D%E0%A4%A5%E0%A4%BE


我正在使用以下小书签生成上面提到的 URL...

javascript:(function(){location.href='https://z3nt6lcj40.execute-api.us-east-1.amazonaws.com/mycall?url='+encodeURIComponent(location.href);})();

您的 lambda 函数中有这一行不引用 URL

url1 = urllib.parse.unquote(url)

来自

'https://zga2tn1wgd.execute-api.us-east-1.amazonaws.com/mycall?url=https://mr.wikipedia.org/wiki/%E0%A4%95%E0%A4%BF%E0%A4%B6%E0%A5%8B%E0%A4%B0%E0%A4%BE%E0%A4%B5%E0%A4%B8%E0%A5%8D%E0%A4%A5%E0%A4%BE'

'https://zga2tn1wgd.execute-api.us-east-1.amazonaws.com/mycall?url=https://mr.wikipedia.org/wiki/किशोरावस्था'

上述结果的非 US-ASCII 部分必须在执行请求之前进行编码。这是在查询组件中。

建议separate URI into its components when encoding它避免改变它的语义。

在向 URL 提出请求之前,还有一些事情要做。

url1 = urllib.parse.unquote(url)
urlparts = urllib.parse.urlparse(url1)
querypart = urllib.parse.parse_qs(urlparts.query)
querypart_enc = urllib.parse.urlencode(querypart)

# Rebuild URL with escaped query part
url1 = urllib.parse.urlunparse((
     urlparts.scheme, urlparts.netloc, 
     urlparts.path, urlparts.params,
     querypart_enc, urlparts.fragment
))