应用层的网络请求
用Requests库,来访问
#使用requests库来访问
import requests
def query(name):
url="http://api.apiopen.top/searchPoetry"
parameters={'name':name}
request=requests.get(url,params=parameters)
content=request.json()
print(name)
print(content['result'][0]['content'])
query('杜甫')
运行结果:
杜甫
万里飘零独此身,诗魂终恋浣花村。|宁贫宁冻宁饥死,一饭何曾忘至尊。
直接用HTTP协议来访问
import http.client
import json
from urllib.parse import quote
base='/searchPoetry'
def query(name):
path='{}?name={}'.format(base,quote(name))
conn=http.client.HTTPConnection('api.apiopen.top')
conn.request('GET',path)
rawreply=conn.getresponse().read()
reply=json.loads(rawreply.decode('utf-8'))
print(name)
print(reply['result'][0]['content'])
query('李白')
这个程序比上一个程序更基础一些。
运行结果:
李白
风骨神仙籍里人,诗狂酒圣且平生。|开元一遇成何事,留得千秋万古名。
用python的网络协议栈的最低层socket实现
import socket
from urllib.parse import quote
request_text="""
GET /searchPoetry?name{} HTTP/1.1\r\n\
Host: api.apiopen.top:80\r\n\
User-Agent: search.py(Foundations of Python Network Programming)\r\n\
Connection: close\r\n\
\r\n\
"""
def search(name):
sock = socket.socket()
sock.connect(('api.apiopen.top', 80))
request=request_text.format(quote(name))
sock.sendall(request.encode('utf-8'))
raw_reply=b''
while True:
more=sock.recv(1024)
if not more:
break
raw_reply+=more
print(raw_reply.decode('utf-8'))
search('杜甫')
运行结果:
HTTP/1.1 200
Server: nginx
Date: Thu, 18 Oct 2018 08:36:27 GMT
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Connection: close
2c
{"code":200,"message":"成功!","result":[]}
0
不知为什么result为空,不知有哪位大佬可以解决下。