使用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_headersparameter towebsockets.connect(), which adds theCookieheader to the initial HTTP handshake. This tells the server you're an authenticated user with the providedPlay Sessionvalue. - 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()becauseawait 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
datain the except block—if the connection fails before receiving any data,datawon't exist, which would throw another error.
Quick Debugging Tips
- Double-check that your
play_sessionvalue is valid (not expired or malformed). - If the server expects specific cookie formatting (like extra attributes), adjust the
Cookieheader 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
相关产品推荐
相关产品推荐

