AS3进行HTTP Basic验证

Kuma post in [About Codes] 2010-3-26 0:18 Friday

        今天写小东西,需要用到HTTP Basic验证,网上找了居多资料都无法解决,群里四处询问,晚上11点20的时候一个群的管理员告诉了俺一个博客地址,打开一看,正式想要的东西,现在分享给大家,原文如下:

I am working on ActionScript3 API for Bloglines services, which requires HTTP Authentication for its two of the services. I was not able to set the header of a HTTP/GET request. Macromedia Flash Player allows you set the header only for POST requests. I discussed this issues with Ted Patrick and he told me how I can us Socket to achieve the desired and he was very kind to give a me code-snippet, which got me started. Thanks Ted.
Finally, I could implement a class(HTTPURLLoader) which allows me to:

  • Add request-headers
  • Do HTTP Authentication for GET URLs
  • Handle HTTP status messages
  • Read the complete response header

It basically connects to a HTTP server on port 80(hardcoded for now) and sends an HTTP/1.0 request so that server closes the connection immediately after response. I could use HTTP/1.1 to keep connection alive and do things. But then closing connection would require some more logic, either a timeout logic if there is no activity on socket then close the connection, or find the end delimiter of response and then close. So I chose the easiest approach :)
I am still working on it and there is a lot(bugs-fixing, optimization, code-commenting, removing hardcoded stuff etc) to be done. I just wanted to share whatever I have done so far. I think, idea is more important than the implementation.
Anyways, I also implemented Base64 in AS3 and also OPML parser for Bloglines. I would soon upload the entire Bloglines AS3 API source.
Download the code:
Usage:-

<mx:Application xmlns:mx="http://www.macromedia.com/2005/mxml" creationComplete="onAppInit()">
<mx:Script>
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import com.abdulqabiz.net.HTTPURLLoader;
import com.abdulqabiz.crypto.Base64;
private var loader:HTTPURLLoader;
private var END_POINT:String = "http://rpc.bloglines.com/";
//you need to set your email/password required for Bloglines access.
private var email:String = "YOUR_EMAIL_FOR_BLOGLINES";
private var password:String = "YOUR_BLOGLINES_PASSWORD";
private function onAppInit()
{
loader = new HTTPURLLoader();
loader.addEventListener("complete", onComplete);
loader.addEventListener("httpStatus", onHTTPStatus);
loader.addEventListener("progress", onProgress);
//for simplicity,not handling following three events.
//loader.addEventListener("close", onClose);
//loader.addEventListener("ioError", onIOError);
//loader.addEventListener("securityError",onSecurityError);
}
private function onComplete(event:Event)
{
//headers stroed as name-value(hash map)
var rh:Object = HTTPURLLoader(event.target).responseHeaders;
var str:String = "";
for(var p:String in rh)    str+= p + ":" + rh[p] + "\n";
console.text+="Response Headers: \n" + str + "\n\n";
//data property holds the content
console.text+="Body Content:\n" + HTTPURLLoader(event.target).data + "\n\n";
}
private function onProgress(event:ProgressEvent)
{
//bytesTotal is not accurate, and its 0 if server doesn't send Content-Length header.
console.text+= "Event: progress:-\n" + "bytesLoaded: " + event.bytesLoaded + "\n\n";
}
private function onHTTPStatus(event:HTTPStatusEvent)
{
//if httpStatus is 401, 403, 404, 500, 501, socket is closed.
console.text+= "Event: httpStatus (" + event.status + ")\n\n";
}
private function loadURL()
{
var request:URLRequest = new URLRequest();
//call listsubs method of Bloglines
request.url = END_POINT + "listsubs";
var credentials:String = Base64.encode(email + ":" + password);
//create HTTP Auth request header
var authHeader:URLRequestHeader = new URLRequestHeader("Authorization","Basic " + credentials);
//add the header to request
request.requestHeaders.push(authHeader);
//make the request.
loader.load(request);
}
</mx:Script>
<mx:Button label="Load URL" click="loadURL()"/>
<mx:TextArea id="console" width="100%" height="100%"/>
</mx:Application>

原文链接:http://www.abdulqabiz.com/blog/archives/2006/03/03/http-authentication-for-httpget-requests-using-actionscript-3/

程序用到的类文章里面有下载链接,上面是一个flex示例,当然你可以在flash中使用它,例如如下代码:

package {
	import com.dynamicflash.util.Base64;
	import com.abdulqabiz.net.HTTPURLLoader;
	import flash.display.*;
	import flash.text.TextField;
	import flash.events.*;
	import flash.net.*;
	import com.adobe.serialization.json.*;
	public class main extends Sprite {
		public function main() {
			var urlR:URLRequest=new URLRequest("http://api.t.cnfol.com/account/verify_credentials.xml");
			var credentials:String = Base64.encode("8850:123456");
			var authHeader:URLRequestHeader = new URLRequestHeader("Authorization","Basic " + credentials);
			urlR.requestHeaders.push(authHeader);
			var loader:HTTPURLLoader=new HTTPURLLoader();
			loader.load(urlR);
			loader.addEventListener("complete", onComplete);
			loader.addEventListener("httpStatus", onHTTPStatus);
			loader.addEventListener("progress", onProgress);
		}
		private function onComplete(event:Event) {
			//headers stroed as name-value(hash map)
			var rh:Object = HTTPURLLoader(event.target).responseHeaders;
			var str:String = "";
			for (var p:String in rh) {
				str+= p + ":" + rh[p] + "\n";
			}
			console.appendText("Response Headers: \n" + str + "\n\n");
			//data property holds the content
			console.appendText("Body Content:\n" + HTTPURLLoader(event.target).data + "\n\n");
		}
		private function onProgress(event:ProgressEvent) {
			//bytesTotal is not accurate, and its 0 if server doesn't send Content-Length header.
			console.appendText( "Event: progress:-\n" + "bytesLoaded: " + event.bytesLoaded + "\n\n");
		}
		private function onHTTPStatus(event:HTTPStatusEvent) {
			//if httpStatus is 401, 403, 404, 500, 501, socket is closed.
			console.appendText( "Event: httpStatus (" + event.status + ")\n\n");
		}
	}
}

老规矩,请勿直接复制上面的ActionScript代码,由于插件问题,其中的某些字符被替换,如下复制,请点击代码框上部的"viewcode"在新视窗中打开复制。

Tags: 标签: as3

引用地址:

小杰
2010-03-26 01:26
哎,如果呢,emlog能有一个和wp那样的,回复一直层叠下去的,多好撒,看起来也美观···
这样的wp插件,研究研究,改过来还是可以滴···
博主回复:那样的插件好麻烦的……等我空闲的时候研究试试吧
小杰
2010-03-26 01:22
哦哦,我也是用emlog。以前一直用的。后来没开博了,现在从新开回来,就接着用。

不知道为什么,刚有一分钟这样子,没法访问你博客
博主回复:呃,是么……
小杰
2010-03-26 01:17
好的,呵呵,多谢了。在你博客,看见很多wp的痕迹···是不是wp的撒?
博主回复:本博客是emlog的……不过这个代码高亮插件原来是WP的插件,叫做WP-codebox一样,我移植到了emlog。但是由于与emlog的编辑器冲突,倒是无法对asp、jsp、php、html代码进行高亮,其他程序代码大部分支持高亮
小杰
2010-03-26 01:14
请问一下,这个程序代码框就是通过调用数据插件实现的吗?
博主回复:不是,我自己移植的插件,由于存在bug,未公开发布,如需使用,你可以在我的博客中找到。

昵称

网址

电邮