python 模拟get,post,delete,put请求应该怎么写

方法一:

使用httplib

import httplib

hostname="localhost"

port=80

method="get" #get,post,put,delete

url="/api/userinfo/get"

body_param='{"uid":3}'

httpheader_json={"content-Type":"application/json","Accept":"application/json"}

 

httpClient=httplib.HTTPConnection(hostname,port)

httpClient.request(method,url,body_param,httpheader_json)

response=httpClient.getresponse()

status=response.status

reason=response.reason

response_header=response.getheaders()

response_body=response.read()

 

方法二:

使用urllib2

import urllib2

url="http://localhost"

param='{"userid":1}'

request=urllib2.Request(url.param)

request.add_header("Content-Type","application/json")

request.add_header("Accept","application/json")

request.get_method=lambda :"GET"#"GET,POST,PUT,DELETE"

response=urllib2.urlopen(request)

response_txt=response.read()

response_header=response.info()

posted @ 2015-12-03 10:39  哲学梦  阅读(3250)  评论(0编辑  收藏  举报