程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python from door to master (7): network-01-interaction with http

編輯:Python

This chapter introduces the simple implementation of the native library Http call , Need to use requests、urllib and http.client library .

One 、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 code
print( u. json) #json Text
print( u. content) # Binary code
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
import
requests

resp = requests. get( 'http://pypi.python.org/pypi?:action=login', auth =( 'user', 'password'))
  • 1.
  • 2.
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)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

Two 、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
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

3、 ... and 、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']
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

Four 、FileUpload

import
requests

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

r = requests. post( url, files = file_list)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

5、 ... and 、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} ')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
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()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved