当前位置 : 主页 > 编程语言 > python >

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

来源:互联网 收集:自由互联 发布时间:2022-06-28
本章会原生的库实现简单的Http调用,需要用到requests、urllib和http.client库。 一、Get import requests from urllib import parse url = 'http://httpbin.org/get' parms = { 'name1' : 'value1' , 'name2' : 'value2' } # Encod

本章会原生的库实现简单的Http调用,需要用到requests、urllib和http.client库。

一、Get

import requests
from urllib import parse

url = 'http://httpbin.org/get'
parms = {
'name1' : 'value1',
'name2' : 'value2'
}

# Encode the query string
querystring = parse.urlencode(parms)

# Make a GET request and read the response
u = requests.get(url+'?' + querystring)

print(u.text) #unicode编码
print(u.json) #json文本
print(u.content) #二进制编码import requests
resp = requests.get('http://pypi.python.org/pypi?:action=login', auth=('user','password'))import requests
url = 'http://pypi.python.org'
# First request
resp1 = requests.get(url)
# Second requests with cookies received on first requests
resp2 = requests.get(url, cookies=resp1.cookies)

二、Post

import requests

url = 'http://httpbin.org/post'

# Dictionary of query parameters (if any)
parms = {
'name1' : 'value1',
'name2' : 'value2'
}

# Extra headers
headers = {
'User-agent' : 'none/ofyourbusiness',
'Spam' : 'Eggs'
}

resp = requests.post(url, data=parms, headers=headers)
text = resp.text

三、Head

resp = requests.get('http://www.python.org')
status = resp.status_code
x_timer = resp.headers['X-Timer']
content_type = resp.headers['Content-Type']
content_length = resp.headers['Content-Length']

四、FileUpload

import requests
url = 'http://httpbin.org/post'
file_list = {'file': ('data.csv', open('data.csv', 'rb'))}

r = requests.post(url, files=file_list)

五、HttpClient

from http.client import HTTPConnection

c = HTTPConnection('www.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.request
auth = urllib.request.HTTPBasicAuthHandler()
auth.add_password('pypi','http://pypi.python.org','username','password')
opener = urllib.request.build_opener(auth)

r = urllib.request.Request('http://pypi.python.org/pypi?:action=login')
u = opener.open(r)
resp = u.read()
网友评论