Android应用H5页面调试WebSocket 403 Forbidden错误解决求助
Android WebView调试WebSocket 403 Forbidden错误解决方法
问题场景
调试Android应用中H5页面时,按以下步骤操作后触发WebSocket连接403错误:
- 将安卓手机连接至Windows电脑
- 开启手机开发者模式
- 在Chrome浏览器输入
chrome://inspect,可正常查看webview页面并打开devtools - 执行命令
adb forward tcp:9222 localabstract::webview_devtools_remote_17180转发套接字进程 - 在Chrome浏览器访问
http://localhost:9225/json,能获取调试列表 - 用Python代码连接列表中的
webSocketDebuggerUrl:
import websocket ws = websocket.WebSocket() ws.connect("ws://localhost:9225/devtools/page/625C5EB348BF3D8E0B359614B7003DE3")
执行后报错:
>>> ws.connect("ws://localhost:9225/devtools/page/625C5EB348BF3D8E0B359614B7003DE3") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\work\MiniConda\lib\site-packages\websocket\_core.py", line 253, in connect self.handshake_response = handshake(self.sock, url, *addrs, **options) File "D:\work\MiniConda\lib\site-packages\websocket\_handshake.py", line 57, in handshake status, resp = _get_resp_headers(sock) File "D:\work\MiniConda\lib\site-packages\websocket\_handshake.py", line 150, in _get_resp_headers raise WebSocketBadStatusException("Handshake status {status} {message} -+-+- {headers} -+-+- {body}".format(status=status, message=status_message, headers=resp_headers, body=response_body), status, status_message, resp_headers, response_body) websocket._exceptions.WebSocketBadStatusException: Handshake status 403 Forbidden -+-+- {'content-length': '239', 'content-type': 'text/html'} -+-+- b'Rejected an incoming WebSocket connection from the http://localhost:9224 origin. Use the command line flag --remote-allow-origins=http://localhost:9224 to allow connections from this origin or --remote-allow-origins=* to allow all origins.'
解决方法
错误提示明确说明:WebSocket连接被拒绝是因为请求来源不在允许列表中,以下两种方案可解决问题:
方案1:修改Chrome启动参数
- 关闭所有Chrome进程:确保所有Chrome窗口和后台进程完全关闭,否则新参数不会生效
- 添加启动参数:右键点击Chrome快捷方式→「属性」,在「目标」栏末尾添加参数(注意和原有内容间加空格):
- 允许所有来源:
--remote-allow-origins=* - 仅允许指定来源(如错误中的
http://localhost:9224):--remote-allow-origins=http://localhost:9224
- 允许所有来源:
- 重新执行调试流程:重启Chrome后,再次执行ADB转发命令,重新尝试WebSocket连接即可
方案2:修改Python请求的Origin头
如果不想修改Chrome启动参数,可在WebSocket连接时手动指定符合要求的Origin头,修改代码如下:
import websocket ws = websocket.WebSocket() ws.connect( "ws://localhost:9225/devtools/page/625C5EB348BF3D8E0B359614B7003DE3", header={"Origin": "http://localhost:9224"} )
内容的提问来源于stack exchange,提问作者xingqu
相关产品推荐
相关产品推荐

