Python从门到精通(七):网络-01-与HTTP交互

网友投稿 299 2022-08-26


Python从门到精通(七):网络-01-与HTTP交互

本章会原生的库实现简单的Http调用,需要用到requests、urllib和requestsfrom urllib import parseurl = '= { 'name1' : 'value1', 'name2' : 'value2'}# Encode the query stringquerystring = parse.urlencode(parms)# Make a GET request and read the responseu = requests.get(url+'?' + querystring)print(u.text) #unicode编码print(u.json) #json文本print(u.content) #二进制编码

import requestsresp = requests.get('auth=('user','password'))

import requestsurl = 'First requestresp1 = requests.get(url)# Second requests with cookies received on first requestsresp2 = requests.get(url, cookies=resp1.cookies)

二、Post

import requestsurl = 'Dictionary of query parameters (if any)parms = { 'name1' : 'value1', 'name2' : 'value2'}# Extra headersheaders = { 'User-agent' : 'none/ofyourbusiness', 'Spam' : 'Eggs'}resp = requests.post(url, data=parms, headers=headers)text = resp.text

三、Head

resp = requests.get('= resp.status_codex_timer = resp.headers['X-Timer']content_type = resp.headers['Content-Type']content_length = resp.headers['Content-Length']

四、FileUpload

import requestsurl = '= {'file': ('data.csv', open('data.csv', 'rb'))}r = requests.post(url, files=file_list)

五、HttpClient

from import HTTPConnectionc = HTTPConnection('python.org', 80)c.request('HEAD', '/index.html')resp = c.getresponse()print(f'Status is: {resp.status}')for name, value in resp.getheaders(): print(f'name is: {name}, value is: {value}')

import urllib.requestauth = urllib.request.HTTPBasicAuthHandler()auth.add_password('pypi','= urllib.request.build_opener(auth)r = urllib.request.Request('= opener.open(r)resp = u.read()


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Python从门到精通(七):网络-02-创建Rest服务接口(python调用rest接口)
下一篇:Python 标准库是什么(python是什么意思)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~