python: HTTP PUT with unencoded binary data

后端 未结 4 2570
难免孤独
难免孤独 2021-02-20 07:09

I cannot for the life of me figure out how to perform an HTTP PUT request with verbatim binary data in Python 2.7 with the standard Python libraries.

I thought I could d

4条回答
  •  情歌与酒
    2021-02-20 07:22

    You're misreading the documentation: urllib2.Request expects the data already encoded, and for POST that usually means the application/x-www-form-urlencoded format. You are free to associate any other, binary data, like this:

    import urllib2
    
    data = b'binary-data'
    r = urllib2.Request('http://example.net/put', data,
                        {'Content-Type': 'application/octet-stream'})
    r.get_method = lambda: 'PUT'
    urllib2.urlopen(r)
    

    This will produce the request you want:

    PUT /put HTTP/1.1
    Accept-Encoding: identity
    Content-Length: 11
    Host: example.net
    Content-Type: application/octet-stream
    Connection: close
    User-Agent: Python-urllib/2.7
    
    binary-data
    

提交回复
热议问题