您的位置:首页 > 理论基础 > 计算机网络

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 json urllib2