11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでBasic認証ヘッダ付きのHTTPを送る

Posted at

PythonでBasic認証ヘッダ付きのHTTPを送るメモ。

urllib2を使うのだが、マニュアルに従うとHTTPPasswordMgrWithDefaultRealmやらHTTPBasicAuthHandlerやら死ぬほどめんどい。

そんな場合は、自分でヘッダを書いてしまえば良い。

話は簡単でauthorizationというヘッダーキーに、 Basic (「ユーザ名:パスワード」のbase64ハッシュ値)という値を入れてあげるだけで良い。

コードで書くと

headers["authorization"] = "Basic " + (user + ":" + pass).encode("base64")[:-1]

でOK。最後の[:-1]は改行コードを削っている。

コード全体は以下のよなう感じ

import urllib2
url = "http://sample.com/index.html"
user = "XXXX"
password = "XXXX"
headers ={}
headers["authorization"] = "Basic " + (user + ":" + password).encode("base64")[:-1]
req = urllib2.Request(url=url, headers=headers)
res = urllib2.urlopen(req)
print(res.read())

めっちゃ簡単だった。

11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?