|
無(wú)聊想調(diào)用下嘀咕的api的時(shí)候,發(fā)現(xiàn)需要HTTP Basic Authentication,就看了下。
什么是HTTP Basic Authentication?直接看http://en.wikipedia.org/wiki/Basic_authentication_scheme吧。
在你訪問(wèn)一個(gè)需要HTTP Basic Authentication的URL的時(shí)候,如果你沒(méi)有提供用戶名和密碼,服務(wù)器就會(huì)返回401,如果你直接在瀏覽器中打開(kāi),瀏覽器會(huì)提示你輸入用戶名和密碼(google瀏覽器不會(huì),bug?)。你可以嘗試點(diǎn)擊這個(gè)url看看效果:http://api.minicloud.com.cn/statuses/friends_timeline.xml
要在發(fā)送請(qǐng)求的時(shí)候添加HTTP Basic Authentication認(rèn)證信息到請(qǐng)求中,有兩種方法:
- 一是在請(qǐng)求頭中添加Authorization:
Authorization: "Basic 用戶名和密碼的base64加密字符串" - 二是在url中添加用戶名和密碼:
http://userName:password@api.minicloud.com.cn/statuses/friends_timeline.xml
下面來(lái)看下對(duì)于第一種在請(qǐng)求中添加Authorization頭部的各種語(yǔ)言的實(shí)現(xiàn)代碼。
先看.NET的吧:
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();
it知識(shí)庫(kù):訪問(wèn)需要HTTP Basic Authentication認(rèn)證的資源的各種語(yǔ)言的實(shí)現(xiàn),轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。