使用urllib2模块构造http post数据结构,提交有文件的表单(multipart/form-data),本示例提交的post表单带有两个参数及一张图片,代码如下:
#buld post body data boundary = '----------%s' % hex(int(time.time() * 1000)) data = [] data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s" ' % 'username') data.append('jack') data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s" ' % 'mobile') data.append('13800138000') data.append('--%s' % boundary) fr=open(r'/var/qr/b.png','rb') data.append('Content-Disposition: form-data; name="%s"; filename="b.png"' % 'profile') data.append('Content-Type: %s ' % 'image/png') data.append(fr.read()) fr.close() data.append('--%s-- ' % boundary) http_url='http://remotserver.com/page.php' http_body=' '.join(data) try: #buld http request req=urllib2.Request(http_url, data=http_body) #header req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary) req.add_header('User-Agent','Mozilla/5.0') req.add_header('Referer','http://remotserver.com/') #post data to server resp = urllib2.urlopen(req, timeout=5) #get response qrcont=resp.read() print qrcont except Exception,e: print 'http error'
C#版本见: