Skip to content

Instantly share code, notes, and snippets.

@dongweiming
Forked from kennethreitz/0_urllib2.py
Last active December 18, 2018 06:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dongweiming/0cde0d2b68b90accc1ded5378db9c284 to your computer and use it in GitHub Desktop.
Save dongweiming/0cde0d2b68b90accc1ded5378db9c284 to your computer and use it in GitHub Desktop.
urllib2 vs requests
# coding=utf-8
import json
import urllib2
from cookielib import CookieJar
hb_url = 'https://httpbin.org/basic-auth/user/pass'
req = urllib2.Request(hb_url)
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, hb_url, 'user', 'pass')
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
cj = CookieJar()
cookie_manager = urllib2.HTTPCookieProcessor(cj)
proxy_handler = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(auth_manager, cookie_manager, proxy_handler)
urllib2.install_opener(opener)
handler = urllib2.urlopen(req)
print handler.getcode()
print handler.headers.getheader('content-type')
data = json.load(handler)
print data['authenticated']
# ------
# 200
# 'application/json'
# True
# coding=utf-8
import requests
hb_url = 'https://httpbin.org/basic-auth/user/pass'
proxies = {
'http': 'http://172.0.0.1',
}
r = requests.get(hb_url, auth=('user', 'pass'), proxies=proxies)
print r.status_code
print r.headers['content-type']
print r.json()['authenticated']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment