This chapter introduces the simple implementation of the native library Http call , Need to use requests、urllib and http.client library .
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 code
print( u. json) #json Text
print( u. content) # Binary code
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)
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
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']
import requests
url = 'http://httpbin.org/post'
file_list = { 'file': ( 'data.csv', open( 'data.csv', 'rb'))}
r = requests. post( url, files = file_list)
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()