無聊想調用下嘀咕的api的時候,發現須要HTTP Basic Authentication,就看了下。javascript
什麼是HTTP Basic Authentication?直接看http://en.wikipedia.org/wiki/Basic_authentication_scheme吧。php
在你訪問一個須要HTTP Basic Authentication的URL的時候,若是你沒有提供用戶名和密碼,服務器就會返回401,若是你直接在瀏覽器中打開,瀏覽器會提示你輸入用戶名和密碼(google瀏覽器不會,bug?)。你能夠嘗試點擊這個url看看效果:http://api.minicloud.com.cn/statuses/friends_timeline.xmlhtml
要在發送請求的時候添加HTTP Basic Authentication認證信息到請求中,有兩種方法:java
下面來看下對於第一種在請求中添加Authorization頭部的各類語言的實現代碼。web
先看.NET的吧:ajax
string
username
=
"
username
"
;
string
password
=
"
password
"
;
//
注意這裏的格式哦,爲 "username:password"
string
usernamePassword
=
username
+
"
:
"
+
password;
CredentialCache mycache
=
new
CredentialCache();
mycache.Add(
new
Uri(url),
"
Basic
"
,
new
NetworkCredential(username, password));
myReq.Credentials
=
mycache;
myReq.Headers.Add(
"
Authorization
"
,
"
Basic
"
+
Convert.ToBase64String(
new
ASCIIEncoding().GetBytes(usernamePassword)));
WebResponse wr
=
myReq.GetResponse();
Stream receiveStream
=
wr.GetResponseStream();
StreamReader reader
=
new
StreamReader(receiveStream, Encoding.UTF8);
string
content
=
reader.ReadToEnd();
你固然也能夠使用HttpWebRequest或者其餘的類來發送請求。api
而後是Python的:跨域
import
urllib2
import
sys
import
re
import
base64
from
urlparse
import
urlparse
theurl
=
'
http://api.minicloud.com.cn/statuses/friends_timeline.xml
'
username
=
'
qleelulu
'
password
=
'
XXXXXX
'
#
你信這是密碼嗎?
base64string
=
base64.encodestring(
'
%s:%s
'
%
(username, password))[:
-
1
]
#
注意哦,這裏最後會自動添加一個\n
authheader
=
"
Basic %s
"
%
base64string
req.add_header(
"
Authorization
"
, authheader)
try
:
handle
=
urllib2.urlopen(req)
except
IOError, e:
#
here we shouldn't fail if the username/password is right
print
"
It looks like the username or password is wrong.
"
sys.exit(
1
)
thepage
=
handle.read()
再來是PHP的:瀏覽器
<?
php
$fp
=
fsockopen
(
"
www.mydomain.com
"
,
80
);
fputs
(
$fp
,
"
GET /downloads HTTP/1.0
"
);
fputs
(
$fp
,
"
Host: www.mydomain.com
"
);
fputs
(
$fp
,
"
Authorization: Basic
"
.
base64_encode
(
"
user:pass
"
)
.
""
);
fpassthru
(
$fp
);
?>
還有flash的AS3的:服務器
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.Base64Encoder;
import mx.rpc.http.HTTPService;
URLRequestDefaults.authenticate
=
false
;
//
設默認爲false,不然用戶較驗錯誤時會彈出驗證框
private
var result:XML;
private
function initApp():
void
{
var base64enc:Base64Encoder
=
new
Base64Encoder;
base64enc.encode(
"
user:password
"
);
//
用戶名和密碼須要Base64編碼
var user:String
=
base64enc.toString();
var http:HTTPService
=
new
HTTPService;
http.addEventListener(ResultEvent.RESULT,resultHandler);
//
監聽返回事件
http.addEventListener(FaultEvent.FAULT,faultHandler);
//
監聽失敗事件
http.resultFormat
=
"
e4x
"
;
//
返回格式
http.url
=
"
http://api.digu.com/statuses/friends_timeline.xml
"
; 以嘀咕網的API爲列
http.headers
=
{
"
Authorization
"
:
"
Basic
"
+
user};
http.send();
}
private
function resultHandler(e:ResultEvent):
void
{
result
=
XML(e.result);
test.dataProvider
=
result.status;
//
綁定數據
}
private
function faultHandler(e:ResultEvent):
void
{
//
處理失敗
}
還有Ruby On Rails的:
class
DocumentsController
<
ActionController
before_filter :verify_access
def show
@document
=
@user.documents.find(params[:id])
end
# Use basic authentication
in
my realm
to
get
a user
object
.
# Since this
is
a security
filter
-
return
false
if
the user
is
not
# authenticated.
def verify_access
authenticate_or_request_with_http_basic(
"
Documents Realm
"
)
do
|username, password|
@user
=
User.authenticate(username, password)
end
end
end
汗,忘記JavaScript的了:
//
須要Base64見:http://www.webtoolkit.info/javascript-base64.html
function
make_base_auth(user, password) {
var
tok
=
user
+
'
:
'
+
pass;
var
hash
=
Base64.encode(tok);
return
"
Basic
"
+
hash;
}
var
auth
=
make_basic_auth(
'
QLeelulu
'
,
'
mypassword
'
);
var
url
=
'
http://example.com
'
;
//
原始JavaScript
xml
=
new
XMLHttpRequest();
xml.setRequestHeader(
'
Authorization
'
, auth);
xml.open(
'
GET
'
,url)
//
ExtJS
Ext.Ajax.request({
url : url,
method :
'
GET
'
,
headers : { Authorization : auth }
});
//
jQuery
$.ajax({
url : url,
method :
'
GET
'
,
beforeSend :
function
(req) {
req.setRequestHeader(
'
Authorization
'
, auth);
}
});
這裏提醒下,HTTP Basic Authentication對於跨域又要發送post請求的用JavaScript是實現不了的(注:對於Chrome插件這類容許經過AJAX訪問跨域資源的,是能夠的)。。
厄~~完!無聊的文章~~~