python发送HTTP POST请求(json格式)到指定网址
from urllib import request import json import hashlib def curlmd5(src): m = hashlib.md5() m.update(src.encode('UTF-8')) return m.hexdigest() def http_post(url, data_json): header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko', 'Content-Type': 'application/json'} jdata = json.dumps(data_json) jdata = bytes(jdata, encoding="utf8") req = request.Request(url, jdata,headers=header_dict) response = request.urlopen(req) return response.read() if __name__=='__main__': key = '24a3b482-3ce8-4cc3-948a-bec575df5d48' chanel = 'TG025600000001' url = 'https://m-dev.xxsxxx.com/api/mxiaodai/userExists' mobileList = ['18321410000','18321410001'] token = curlmd5(key + mobileList[0]) print(token) data_json ={'mobileList': mobileList, 'channel': chanel, 'token': token } resp = http_post(url, data_json) returnmessge = resp.decode(encoding='utf-8') print(returnmessge) 5. Django后端处理json格式的POST请求 def handle_post(request): if request.POST: req = json.loads(request.body) name = req.get('name') job = req.get('job') print(name,job) return_json = json.dumps((name,job)) return HttpResponse(return_json) else: return_json = 'POST only!' return HttpResponse(return_json)