You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用WebSocket Client API连接出错:403状态码问题求助

Hey there! That 403 error is telling you the server isn't authorizing your connection—because you're not passing the required Play Session cookie when initiating the WebSocket handshake. Let's get this sorted out step by step.

The Root Cause

WebSocket connections start with an HTTP handshake, so you need to send your authentication cookie as part of that initial HTTP request. Your current code doesn't include any custom headers, so the server can't verify your identity and rejects the connection.

Modified Working Code

Here's the corrected version of your code with cookie support and fixes for other small issues:

import websockets

async def streaming_data(url, play_session):
    try:
        # Inject the Play Session cookie into the handshake headers
        extra_headers = {
            "Cookie": f"Play Session={play_session}"
        }
        
        async with websockets.connect(url, extra_headers=extra_headers) as websocket:
            # websocket.recv() returns the message directly, no need for read()
            response = await websocket.recv()
            print("Received data:", response)
            
    except Exception as e:
        print('Error in making the Websocket Connection!!')
        print(e.args)
        # Avoid printing 'data' here—it won't exist if the error happens before receiving any content

Key Fixes & Explanations

  • Cookie Authentication: We added the extra_headers parameter to websockets.connect(), which adds the Cookie header to the initial HTTP handshake. This tells the server you're an authenticated user with the provided Play Session value.
  • Typo Correction: Fixed reponse → response (that spelling mistake would have caused an extra exception even if the connection worked).
  • Proper Data Handling: Removed data = response.read() because await websocket.recv() already returns the raw message content as a string or bytes (depending on the server's setup).
  • Safer Exception Handling: We stopped referencing data in the except block—if the connection fails before receiving any data, data won't exist, which would throw another error.

Quick Debugging Tips

  • Double-check that your play_session value is valid (not expired or malformed).
  • If the server expects specific cookie formatting (like extra attributes), adjust the Cookie header string to match what your browser sends (you can check this in your browser's dev tools Network tab when a WebSocket connects).

内容的提问来源于stack exchange,提问作者blackpanther05

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:34:51