要在發送請求的時候添加HTTP Basic Authentication認證資訊到請求中,有兩種方法:
- 一是在要求標頭中添加Authorization:
Authorization: "Basic 使用者名稱和密碼的base64加密字串"
- 二是在url中添加使用者名稱和密碼:
http://userName:password@api.minicloud.com.cn/statuses/friends_timeline.xml
下面來看下對於第一種在請求中添加Authorization頭部的各種語言的實現代碼。
先看.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();
你當然也可以使用HttpWebRequest或者其他的類來發送請求。