Recently in the use of Python interface testing, found Python in the HTTP request method There are many kinds of, today take some time to organize the relevant content, to share with you, the specific content is as follows:
One, Python comes with library----URLLIB2
Python comes with a library urllib2 used more, simple to use as follows:
Import Urllib2
Response = Urllib2.urlopen (' http://localhost:8080/jenkins/api/json?pretty=true ')
Print Response.read ()
A simple GET request
Import Urllib2
Import Urllib
Post_data = Urllib.urlencode ({})
Response = Urllib2.urlopen (' http://localhost:8080/, Post_data)
Print Response.read ()
Print Response.getheaders ()
This is the simplest urllib2 send post example. More code
Ii. python comes with library--httplib
Httplib is a relatively low-level HTTP request module, Urlib is based on httplib encapsulation. Simple to use as follows:
12345678910 |
import httplib
conn
=
httplib.HTTPConnection(
"www.python.org"
)
conn.request(
"GET"
,
"/index.html"
)
r1
=
conn.getresponse()
print
r1.status, r1.reason
data1
=
r1.read()
conn.request(
"GET"
,
"/parrot.spam"
)
r2
=
conn.getresponse()
data2
=
r2.read()
conn.close()
|
A simple GET request
Let's look at the POST request again
123456789 |
import
httplib, urllib
params
=
urllib.urlencode({
‘@number‘
:
12524
,
‘@type‘
:
‘issue‘
,
‘@action‘
:
‘show‘
})
headers
=
{
"Content-type"
:
"application/x-www-form-urlencoded"
,
"Accept"
:
"text/plain"
}
conn
=
httplib.HTTPConnection(
"bugs.python.org"
)
conn.request(
"POST"
, "", params, headers)
response
=
conn.getresponse()
data
=
response.read()
print
data
conn.close()
|
I think it's too complicated. Every time you write, you have to go through the document again, look at the third.
Iii. third-party library--requests
Sending a GET request is super simple:
1 |
print requests.get(‘http: //localhost :8080).text |
Just a word, then look at the POST request
123 |
payload = { ‘key1‘ : ‘value1‘ , ‘key2‘ : ‘value2‘ } r = requests.post( "http://httpbin.org/post" , data = payload) print r.text |
Also very simple.
Look again if you want to certify:
12345 |
url = ' http://localhost:8080 ' r = requests.post (url, data = {}, auth = httpbasicauth ( ' admin ' , ' admin ' ) print r.status_code print r.headers print r.reason |
Is it much simpler than URLLIB2, and the requests comes with JSON parsing. This is great.
HTTP requests in Python
12345 |
import urllib params = urllib.urlencode({key:value,key:value}) resultHtml = urllib.urlopen( ‘[API or 网址]‘ ,params) result = resultHtml.read() print result |
HTTP request Method Library rollup in Python