【Python】使用Python调用Rest接口

用SpringBoot写了一个几个简单的Rest接口,对一个计数器进行查询,设置和增加,具体可以看:

https://www.cnblogs.com/wuyizuokan/p/11117294.html

废话不多说,直接上Python代码:

 1 # -*- coding: utf-8 -*-
 2 import json
 3 
 4 import requests
 5 
 6 REQUEST_URL = "http://localhost:8080/me/count"
 7 HEADER = {'Content-Type':'application/json; charset=utf-8'}
 8 
 9 # 查询Count的值
10 def getCount():
11     rsp = requests.get(REQUEST_URL)
12     if rsp.status_code == 200:
13         rspJson = json.loads(rsp.text.encode())
14         return rspJson["count"]
15     else:
16         return -1
17 
18 # 设置Count的值
19 def setCount(count):
20     requestDict = {'count': count}
21     rsp = requests.put(REQUEST_URL, data = json.dumps(requestDict),headers = HEADER)
22     if rsp.status_code == 200:
23         return True
24     else:
25         return False
26 
27 # 增加Count
28 def addCount(count):
29     requestDict = {'count':count}
30     rsp = requests.post(REQUEST_URL, data=json.dumps(requestDict), headers=HEADER)
31     if rsp.status_code == 200:
32         return True
33     else:
34         return False
35 
36 # 程序入口函数
37 if __name__=="__main__":
38     isSuccess = setCount(100) # 测试设置Count
39     print(isSuccess)
40     addCount(200) # 测试增加Count
41     count = getCount() # 测试查询Count
42     print(count)

先启动SpringBoot服务:

运行Python代码的结果:

 

猜你喜欢

转载自www.cnblogs.com/wuyizuokan/p/11185214.html
今日推荐