-
-
Save dongweiming/0cde0d2b68b90accc1ded5378db9c284 to your computer and use it in GitHub Desktop.
urllib2 vs requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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