发布时间:2019-08-15 10:07:36编辑:auto阅读(1687)
实际工作中,需要用到python来对服务器进行请求(也是方便进行接口自动化),因为,本文来记录一下python是如何来进行get和post请求的,本文针对python的httplib模块介绍get和post请求,urllib模块直接进行请求
1、httplib模块之get请求,直接上代码。
#coding=utf-8
import httplib,urllib
import json
httpClient=None
try:
httpClient=httplib.HTTPConnection('test.web.com',80,timeout=30)#注意,此处域名不要带http://
headers={'Accept':'application/json','cookie':'PHPSESSID=xxxxx'}#如果有headers的话就带上。没有则不用
httpClient.request(method='GET',url='/main/?r=get/student',headers=headers)
response=httpClient.getresponse()
data=json.load(response,encoding='utf-8')#将获取到的内容转换为json类型数据
except Exception,e:
raise e
finally:
if httpClient:
httpClient.close()
#coding=utf-8
import httplib,urllib
import json
httpClient=None
try:
httpClient=httplib.HTTPConnection('test.web.com',80,timeout=30)#注意,此处域名不要带http://
headers={'Content-type':'application/x-www-form-urlcoded','Accept':'text/plain','cookie':'PHPSESSID=xxxxx'}#post请求头需要有content-type,否则失败
#尝试过,不知道为啥。。
params=urllib.urlencode({"ID:292})#post的参数,这里需要是一个对象的形式
httpClient.request('POST','/main/?r=get/student',params,headers)#这里可以不带key,直接用value
response=httpClient.getresponse()
data=json.load(response,encoding='utf-8')#将获取到的内容转换为json类型数据
print "name=%s"%(data['name'])#直接读取
except Exception,e:
raise e
finally:
if httpClient:
httpClient.close()
response=urllib.urlopen('http://test.web.com/main/?r=get/student&ID=%s'%(stu_id))#id自己定义
上一篇: Hive UDF Python
下一篇: python版js压缩工具
49336
48523
39223
36314
30727
27541
26535
21358
21207
19556
197°
410°
414°
502°
830°
580°
1248°
1299°
1193°
1181°