Python study notes 7-network programming

import urllib.request
import json,requests

# urlib module, not commonly used 
url = ' http://api.nnzhp.cn/api/user/stu_info?stu_name=little black horse ' 
res = urllib.request.urlopen(url)
jieguo =res.read().decode() #The   return value is all Byte type, which needs to be transcoded 
print (json.loads(jieguo))


#Send get request 
url = ' http://api.nnzhp.cn/api/user/stu_info?stu_name=Little Dark Horse ' 
req = requests.get(url) #Send get request 
print (req.text) #Get result 
print (req.json()) #The result obtained is directly a dictionary. The json string must be returned before the .json method can be used.

#Send post request 
url = ' http://api.nnzhp.cn/api/user/login ' 
data = { ' username ' : ' niuhanyang ' , ' passwd ' : ' aA123456 ' }
req = requests.post(url,data) #Send a post request, the first parameter is the url, and the second parameter is the requested data 
print (req.json())

#The input parameter is the 
url of json = ' http://api.nnzhp.cn/api/user/add_stu ' 
data = { ' name ' : ' Ding Fei ' , ' grade ' : ' Cancer ' , ' phone ' :31971891223 } #The dictionary is passed 
req = requests.post(url,json=data) #Send a post request, the first parameter is the url, and the second parameter is the requested data 
print (req.json())

#添加cookie
url = 'http://api.nnzhp.cn/api/user/gold_add'
data =  {'stu_id':231,'gold':1000}
cookie = {'niuhanyang':'6d195100b95a43046d2e385835c6e2c2'}
req = requests.post(url,data,cookies=cookie)
print(req.json())

#添加header
url='http://api.nnzhp.cn/api/user/all_stu'
mpp = {'Referer':'http://api.nnzhp.cn/','User-Agent':'Chore'}
res = requests.get(url,headers=mpp)
print(res.json())

#上传文件
url = 'http://api.nnzhp.cn/api/file/file_upload'
f = open(r'C:\Users\bjniuhanyang\Desktop\ad.cpm.schedulingInfo.v1.json','rb')
r = requests.post(url,files={'file':f})
print(r.json())

#download file 
url= ' http://www.besttest.cn/data/upload/201710/f_36b1c59ecf3b8ff5b0acaf2ea42bafe0.jpg ' 
r   = requests.get(url)
 print (r.status_code) #Get   the status code of the request 
print (r. content)   #Get the returned result in binary format 
fw = open(r ' bt.jpg ' , ' wb ' )
fw.write(r.content)
fw.close()

#Save web page 
url = ' http://www.nnzhp.cn/archives/630 ' 
r = requests.get(url)
f = open('nnzhp.html','wb')
f.write(r.content)
f.close()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324936964&siteId=291194637