HTTP POST binary files using Python: concise non-pycurl examples?

前端 未结 5 1206
-上瘾入骨i
-上瘾入骨i 2021-02-06 13:29

I\'m interested in writing a short python script which uploads a short binary file (.wav/.raw audio) via a POST request to a remote server.

I\'ve done this with pycurl,

5条回答
  •  再見小時候
    2021-02-06 14:00

    I met similar issue today, after tried both and pycurl and multipart/form-data, I decide to read python httplib/urllib2 source code to find out, I did get one comparably good solution:

    1. set Content-Length header(of the file) before doing post
    2. pass a opened file when doing post

    Here is the code:

    import urllib2, os
    image_path = "png\\01.png"
    url = 'http://xx.oo.com/webserviceapi/postfile/'
    length = os.path.getsize(image_path)
    png_data = open(image_path, "rb")
    request = urllib2.Request(url, data=png_data)
    request.add_header('Cache-Control', 'no-cache')
    request.add_header('Content-Length', '%d' % length)
    request.add_header('Content-Type', 'image/png')
    res = urllib2.urlopen(request).read().strip()
    return res
    

    see my blog post: http://www.2maomao.com/blog/python-http-post-a-binary-file-using-urllib2/

提交回复
热议问题