简体   繁体   中英

Adding headers and cookies in Web Socket open connection request in Python

To authenticate myself I need to add an authentication cookie and some header fields and value while I am opening a connection with web socket server. I have explored a lot but could not find any simple clear cut Python library that helps me do that.

You can use Requests library: docs.python-requests.org

AutobahnPython supports both inspecting and setting HTTP headers during the WebSocket opening handshake. See here and here .

If it fits your needs, you could check out the urllib and urllib2 libraries. They're higher level libraries, that let you do this kind of stuff fairly easily. For example, sending a request with certain header fields would look like this:

import urllib2
import urllib

#POST data you might want to send. If you don't want to send post data, just set this as None or blank, e.g. data = {}
data = urllib.urlencode({"username":uname, "passwd":yourpass, "submit":"Submit"})
#add as many header fields as you like
headers = {"Cookie":"<<your cookies go here>>", "Referer":"blahblah"} 

request = urllib2.Request("yourwebserver.com", data, headers)
#here you get your response back
response = urllib2.urlopen(request).read()

Hope this is some help to you! Cheers!:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM