Python(Python2和Python3)中后台执行Get和Post有一些方法,本文主要介绍使用requests、urllib2、httplib2、http.client执行Get和Post请求方法及示例代码。

1、使用requests执行

requests在Python2和Python3用法基本相同,有小的区别:python3中response.text是str数据类型,而response.content是bytes类型,python2中response.text是unicode数据类型,而response.content是字符串类型。

相关文档https://2.python-requests.org//zh_CN/latest/user/quickstart.html

import requests
url = 'https://...'
payload = {'key1': 'value1', 'key2': 'value2'}
# GET
r = requests.get(url)
# GET with params in URL
r = requests.get(url, params=payload)
# POST with form-encoded data
r = requests.post(url, data=payload)
# POST with JSON 
import json
r = requests.post(url, data=json.dumps(payload))
# Response, status etc
r.text
r.status_code

2、使用urllib2执行

urllib2模块在Python 3中名为分成urllib.request 和 urllib.error。在将源代码转换为Python 3时,2to3工具将自动适应导入。

相关文档https://docs.python.org/2/library/urllib2.html

def URLRequest(url, params, method="GET"):
    if method == "POST":
        return urllib2.Request(url, data=urllib.urlencode(params))
    else:
        return urllib2.Request(url + "?" + urllib.urlencode(params))

3、使用httplib2执行

相关文档

https://github.com/jcgregorio/httplib2
https://github.com/httplib2/httplib2/wiki/Examples
https://github.com/httplib2/httplib2/wiki/Examples-Python3

1) Python2中执行

#!/usr/bin/env python
import urllib
import httplib2
http = httplib2.Http()
url = 'http://www.example.com/login'   
body = {'USERNAME': 'foo', 'PASSWORD': 'bar'}
headers = {'Content-type': 'application/x-www-form-urlencoded'}
response, content = http.request(url, 'POST', headers=headers, body=urllib.urlencode(body))
headers = {'Cookie': response['set-cookie']}
url = 'http://www.example.com/home'   
response, content = http.request(url, 'GET', headers=headers)

2) Python3中执行

#!/usr/bin/python3
import urllib.parse
import httplib2
http = httplib2.Http()
url = 'http://www.example.com/login'   
body = {'USERNAME': 'foo', 'PASSWORD': 'bar'}
headers = {'Content-type': 'application/x-www-form-urlencoded'}
response, content = http.request(url, 'POST', headers=headers, body=urllib.parse.urlencode(body))
headers = {'Cookie': response['set-cookie']}
url = 'http://www.example.com/home'   
response, content = http.request(url, 'GET', headers=headers)

4、Python3使用http.client执行

相关文档https://docs.python.org/3/library/http.client.html

#!/usr/bin/env python3
import http.client
import json
print("\n GET example")
conn = http.client.HTTPSConnection("httpbin.org")
conn.request("GET", "/get")
response = conn.getresponse()
data = response.read().decode('utf-8')
print(response.status, response.reason)
print(data)

print("\n POST example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body = {'text': 'testing post'}
json_data = json.dumps(post_body)
conn.request('POST', '/post', json_data, headers)
response = conn.getresponse()
print(response.read().decode())
print(response.status, response.reason)

print("\n PUT example ")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing put'}
json_data = json.dumps(post_body)
conn.request('PUT', '/put', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)

print("\n delete example")
conn = http.client.HTTPSConnection('httpbin.org')
headers = {'Content-type': 'application/json'}
post_body ={'text': 'testing delete'}
json_data = json.dumps(post_body)
conn.request('DELETE', '/delete', json_data, headers)
response = conn.getresponse()
print(response.read().decode(), response.reason)
print(response.status, response.reason)

推荐文档

相关文档

大家感兴趣的内容

随机列表