python使用urllib2发送http请求
2016-05-31 16:58
330 查看
# -*-coding:utf8-*- import re import json import urllib import urllib2 from poster.encode import multipart_encode from poster.streaminghttp import register_openers # ## # @param url:请求地址,字符串,http://xxx.xx.com/xx # @param method: 请求方式,字符串,仅支持GET、POST、PUT、DELETE、HEAD # @param user_header:请求头,字典,{"key":"value"} # @param request_body_type:请求体类型,字符串,仅支持form-data、x-www-form-urlencoded、raw格式 # @param request_body_data:请求体,字符串或者字典。 # # 1、如果是form-data、x-www-form-urlencoded格式的,传字典; # # 2、如果是raw格式的,可传字典或字符串。 # ## def get_api_response(url, method, user_header, request_body_type, request_body_data): try: # GET请求 if re.match(method, "get", re.IGNORECASE): request = urllib2.Request(url) # POST请求/PUT请求 elif re.match(method, "post", re.IGNORECASE) or re.match(method, "put", re.IGNORECASE): # 处理form-data格式请求体 if re.match(request_body_type, "form-data", re.IGNORECASE): register_openers() # headers 包含必须的 Content-Type 和 Content-Length # data 是一个生成器对象,返回编码过后的参数 data, headers = multipart_encode(request_body_data) request = urllib2.Request(url, data, headers) # 处理x-www-form-urlencoded格式请求体 elif re.match(request_body_type, "x-www-form-urlencoded", re.IGNORECASE): data = urllib.urlencode(request_body_data) request = urllib2.Request(url, data) # 处理raw格式请求体 elif re.match(request_body_type, "raw", re.IGNORECASE): if type(request_body_data) == str: data = json.JSONDecoder().decode(request_body_data) else: data = request_body_data if type(data) == list: data = json.JSONEncoder().encode(data) else: data = urllib.urlencode(data) request = urllib2.Request(url, data) if re.match(method, "put", re.IGNORECASE): request.get_method = lambda: 'PUT' # DELETE请求 elif re.match(method, "delete", re.IGNORECASE): request = urllib2.Request(url) request.get_method = lambda: 'DELETE' # HEAD请求 else: request = urllib2.Request(url) request.get_method = lambda: 'HEAD' # 统一添加请求头 if user_header: for keys in user_header: request.add_header(keys, user_header[keys]) response = urllib2.urlopen(request) result_data = response.read() response_code = response.code except urllib2.HTTPError, e: result_data = "" response_code = e.code result = {"code": response_code, "data": result_data} return result
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- 使用 Python 处理 JSON 格式的数据
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例