0
点赞
收藏
分享

微信扫一扫

看漫画学Python 第十四章代码

年迈的代码机器 2022-03-23 阅读 82

14.3.1 发送GET请求

import urllib.request

url = 'http://localhost:8000/NoteWebService/note.do?/action=query10'

req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
data = response.read()
json_data = data.decode()
print(json_data)

14.3.2 发送POST请求

import urllib.request

url = 'http://localhost:8080/NoteWebService/note.do'

params_dict = {'action':'query','ID':'10'}
params_str = urllib.parse.urlencode(params_dict)
print(params_str)

params_bytes = params_str.encode()

req = urllib.request.Request(url,data = params_bytes) #
with urllib.request.urlopen(req) as response:
data = response.read()
json_data = data.decode()
print(json_data)

14.4.2 JSON数据的解码

import urllib.request
import json

url = 'http://localhost:8000/NoteWebService/note.do?/action=query10'

req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
data = response.read()
json_data = data.decode()
print("JSON字符串:",json_data)

py_dict = json.loads(json_data)
print("备忘录ID:",py_dict['ID'])
print("备忘录日期:",py_dict['CDate'])
print("备忘录内容:",py_dict['Content'])
print("用户ID:",py_dict['UserID'])

14.5 下载图片示例

import urllib.request

url = 'http://localhost:8080/NoteWebService/logo.png'

req = urllib.request.Request(url)
with urllib.request.urlopen(url) as response:
data = response.read()
f_name = 'download.png'
with open(f_name,'wb') as f:
f.write(data)
print('数据下载成功')

14.6 返回所有备忘录信息

import urllib.request
import json

url = 'http://localhost:8080/NoteWebService/note.do'

req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
data = response.read()
json_data = data.decode()

py_dict = json.loads(json_data)
#返回所有的备忘录记录信息
record_array = py_dict['Record']

for record_obj in record_array:
print('--------备忘录信息--------')
print("备忘录ID:",py_dict['ID'])
print("备忘录日期:",py_dict['CDate'])
print("备忘录内容:",py_dict['Content'])
print("用户ID:",py_dict['UserID'])
举报

相关推荐

0 条评论