python http请求的几种方式的实现
直接上代码:
import os
import sys
import json
import urllib2
class CHttp:
def __init__(self):
pass;
def Get(self, strUrl, mapVal):
if mapVal:
if -1 == strUrl.find('?'):
strUrl += '?'
strUrl = strUrl.rstrip('&');
for strKey, strVal in mapVal.items():
strUrl += '&%s=%s' %(strKey, strVal);
strUrl = strUrl.replace('?&', '?');
oResp = urllib2.urlopen(strUrl);
return oResp.read();
def Post(self, strUrl, mapVal):
oReq = urllib2.Request(strUrl, json.dumps(mapVal));
oResp = urllib2.urlopen(oReq);
return oResp.read();
def Put(self, strUrl, mapVal, strContentType = ''):
oReq = urllib2.Request(strUrl, json.dumps(mapVal));
if strContentType:
oReq.add_header('Content-Type', strContentType);
oReq.get_method = lambda : 'PUT';
oResp = urllib2.urlopen(oReq);
return oResp.read();
def Delete(self, strUrl, mapVal, strContentType = ''):
oReq = urllib2.Request(strUrl, json.dumps(mapVal));
if strContentType:
oReq.add_header('Content-Type', strContentType);
oReq.get_method = lambda : 'DELETE';
oResp = urllib2.urlopen(oReq);
oResp.read();