最近在处理服务器接口的时候,需要使用Python
模拟发送表单数据到服务器,搜索了一下,找到如下例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# encoding=utf8 import urllib import urllib2 import httplib import os HOST = 'xx.xx.xx.xx' PORT = 8000 P_ID = xx U_NAME = 'xxx' API_KEY = 'xxx' API_SEC = 'xxx' UP_APK = xx def sign(src, key): HEX_CHARS = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ] from hashlib import sha1 import hmac hashed = hmac.new(key, src, sha1) sv = str(hashed.digest()) ret = '' for b in bytearray(sv): bite = b & 0xff ret += HEX_CHARS[ bite >> 4 ] ret += HEX_CHARS[ bite & 0xf ] return ret def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ import random BOUNDARY = '----------%s' % ''.join(random.sample('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ', 62)) CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append('Content-Type: %s' % get_content_type(filename)) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body, BOUNDARY def get_content_type(filename): import mimetypes return mimetypes.guess_type(filename)[0] or 'application/octet-stream' def post_apk_sign(apk_file): filename = os.path.basename(apk_file) url = 'http://' + HOST + ':' + str(PORT) + 'xxx' fields = [('un', U_NAME), ('p_id', str(P_ID)), ('up_type', str(UP_APK))] with open(apk_file, 'r') as f: files = [('apk_file', filename, f.read())] content_type, body, boundary = encode_multipart_formdata(fields, files) si = sign(API_KEY + str(P_ID) + str(UP_APK) + U_NAME, API_SEC) # print si req = urllib2.Request(url) req.add_header('api_key', API_KEY) req.add_header('sign', si) req.add_header('Content-Type', 'multipart/form-data; boundary='+boundary) resp = urllib2.urlopen(req, body) res = resp.read() print res if __name__=='__main__': # b38d73bb278800dd3c0c3cf11ad20c106d17944c # print(sign(b'123test123456', b'456')) apk_file = 'xxx.apk' post_apk_sign(apk_file) |