PYTHON Comment faire une requete http
Faire des requetes grace a python et httplib
La class HttpRequest
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #!/usr/bin/python import httplib import urllib class HttpRequest: def __init__(self, proxyhost, proxyport): self.proxyhost = proxyhost self.proxyport = proxyport self.cnx = httplib.HTTPConnection(self.proxyhost, self.proxyport, 20) def get(self, url): self.cnx.request("GET", url) response = self.cnx.getresponse() print("url: %s, %s %s"%(url, response.status, response.reason)) self.msg = response.msg self.content = response.read() def post(self, url, params = ''): headers = {"Content-type":"application/x-www-form-urlencoded", "Accept":"text/plain"} if(len(params) > 0): params = urllib.urlencode(params) self.cnx.request("POST", url, params, headers) response = self.cnx.getresponse() print("url: %s, %s %s"%(url, response.status, response.reason)) self.msg = response.msg self.content = response.read() def getresponse(self): print(self.msg) def getcontent(self): print(self.content) def __del__(self): self.cnx.close() |
httprequest = HttpRequest("127.0.0.1", "3777")
En GET
httprequest.get('http://www.google.fr') httprequest.get('http://blog.hio.fr') httprequest.get('http://blog.hio.fr/blu.html') httprequest.get('http://blog.if-else.fr')
Renvoi
url: http://www.google.fr, 200 OK url: http://blog.hio.fr, 200 OK url: http://blog.hio.fr/blu.html, 404 Not Found url: http://blog.if-else.fr, 200 OK
En POST
params = {"login":"login", "password":"password"} httprequest.post('http://www.url-bidon.fr/login/connexion', params)
Renvoi par exemple
url: http://www.url-bidon.fr/login/connexion, 302 Moved Temporarily
Et si on veut en savoir plus on a les fonctions getresponse() et getcontent()
httprequest.getresponse()
Renvoi
Date: Sun, 15 Nov 2009 11:04:55 GMT Server: Apache X-Powered-By: PHP/5.2.6-1+lenny3 Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Set-Cookie: PHPSESSID=d1d0958e52fb25b874a573bd1c261b1a; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Location: /login/failed Vary: Accept-Encoding Content-Length: 0 Content-Type: text/html; charset=utf-8 X-Cache: MISS from proxy.hio.fr X-Cache-Lookup: MISS from proxy.hio.fr:3777 Via: 1.0 proxy.hio.fr (squid/3.0.STABLE8) Proxy-Connection: close
httprequest.getcontent()
Renvoi le contenu de la page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> etc...