最近在学习Python,主要用于编写测试用例。作用软件pycharm,接触到Python中的request对象了,用于发送请求。发请求时先拼接请求头header。
def post(self, url, param_dict, param_header, file='', param_type='x-www-form-urlencode'): """ @功能:封装post方式 @paramType:指传入参数类型,可以是form-data、x-www-form-urlencode、json """ respone_code = None respone = None try: if param_type == 'x-www-form-urlencode': params = param_dict elif param_type == 'json': params = json.dumps(param_dict) if file == '': ret = requests.post(self.Server + url, data=params, headers=param_header) else: files = {'file': open(file, 'rb')} ret = requests.post(self.Server + url, data=params, headers=param_header, files=files) respone_code = ret.status_code respone = ret.text except requests.HTTPError, e: respone_code = e.getcode() respone = e.read().decode("utf-8") print respone_code#, respone return respone_code, respone
param_header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',"Content-Type": "application/json"}