Home>

Recently using python for interface testing,I found that there are many kinds of http request methods in python.Take some time today to organize related content.Friends who are interested in python http request related knowledge

Recently using python for interface testing,I found that there are many kinds of http request methods in python.Take some time today to organize related content.Share with everyone,The details are as follows:

First, python comes with a library-urllib2

Python comes with more library urllib2,Simple use is as follows:

import urllib2
response=urllib2.urlopen ("http://localhost:8080/jenkins/api/json?pretty=true")
print response.read ()

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 example of urllib2 sending a post. More code

Second, python comes with library-httplib

httplib is a relatively low-level http request module.Urlib is based on httplib. Simple use is as follows:

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 ()

Simple get request

Let's look at the post request again

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 ()

Does it feel too complicated?Every time I write, I have to turn over the document.Look at the third one

Third-party libraries-requests

Sending a get request is super simple:

print requests.get ("http://localhost:8080) .text

In a word,Look at the post request again

payload={"key1":"value1", "key2":"value2"}
r=requests.post ("http://httpbin.org/post", data=payload)
print r.text

It's also very simple.

Look again if i want to authenticate:

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 requests comes with json parsing. This is great

http request in python

import urllib
params=urllib.urlencode ((key:value, key:value))
resulthtml=urllib.urlopen ("[api or url]", params)
result=resulthtml.read ()
print result
  • Previous Detailed explanation of Jiugong coordinate calculation and dictionary conversion model in iOS application UI development
  • Next JS implementation of the page jump progress bar used directly