I was trying to post a png file to our internal webserver for some quick and dirty task, but Python keep throwing ascii encoding exception.
In the end I decide to dig into Python’s httplib and urllib2 to find out what’s going on, if that doesn’t work I will fallback to raw TCP socket solution.
Luckily I got the following solution that works like a charm:
1. set Content-Length header(of the file) before doing post
2. pass a opened file when doing post
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('Content-Length', '%d' % length)
res = urllib2.urlopen(request).read().strip()