python: HTTP PUT with unencoded binary data

后端 未结 4 2543
难免孤独
难免孤独 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:35

    This snipped worked for me to PUT an image:

    on HTTPS site. If you don't need HTTPS, use httplib.HTTPConnection(URL) instead.

    import httplib
    import ssl
    API_URL="api-mysight.com"
    TOKEN="myDummyToken"
    IMAGE_FILE="myimage.jpg"
    imageID="myImageID"
    URL_PATH_2_USE="/My/image/" + imageID +"?objectId=AAA"
    headers = {"Content-Type":"application/octet-stream", "X-Access-Token": TOKEN}
    imgData = open(IMAGE_FILE, "rb")
    REQUEST="PUT"
    conn = httplib.HTTPSConnection(API_URL, context=ssl.SSLContext(ssl.PROTOCOL_TLSv1))
    conn.request(REQUEST, URL_PATH_2_USE, imgData, headers)
    response = conn.getresponse()
    result = response.read()
    

提交回复
热议问题