BotanSS/net/HttpRequest.js

122 lines
2.2 KiB
JavaScript
Raw Normal View History

2016-02-11 00:16:16 +00:00
"use strict";
var EventEmitter = require( "events" ).EventEmitter;
var http = require( "http" );
var https = require( "https" );
class HttpRequestCompleteEventArgs
{
2016-02-28 21:46:29 +00:00
constructor( Response, ResponseData )
2016-02-11 00:16:16 +00:00
{
2016-02-28 21:46:29 +00:00
this.statusCode = Response.statusCode;
2016-02-11 00:16:16 +00:00
this.Data = ResponseData;
2016-02-28 21:46:29 +00:00
this.Response = Response;
}
get Headers()
{
return this.Response.headers;
2016-02-11 00:16:16 +00:00
}
get ResponseString()
{
return this.Data.toString( "utf-8" );
}
}
class HttpRequest extends EventEmitter
{
constructor( Url, Headers )
{
super();
this.SetUrl( Url );
this.Method = "GET";
this.Headers = Headers || {
"User-Agent": "BotanSS HttpRequest"
};
2016-03-21 17:16:24 +00:00
this.Secured = false;
2016-02-11 00:16:16 +00:00
}
SetUrl( Url )
{
var Match = Url.match( "^https?://" );
if( !Match ) throw new Error( "Invalid Protocol" );
switch( Match[0] )
{
case "http://":
Url = Url.substr( 7 );
this.Port = 80;
break;
case "https://":
Url = Url.substr( 8 );
this.Port = 443;
2016-03-21 17:16:24 +00:00
this.Secured = true;
2016-02-11 00:16:16 +00:00
break;
}
let slash = Url.indexOf( "/" ) ;
if( slash < 0 )
{
this.Path = "/";
this.Hostname = Url;
}
else
{
this.Path = Url.substr( slash );
this.Hostname = Url.substr( 0, slash );
}
}
PostData( Data )
{
this.Method = "POST";
this.Headers[ "Content-Type" ] = "application/x-www-form-urlencoded";
this.RawPostData = new Buffer( Data );
this.Headers[ "Content-Length" ] = this.RawPostData.length;
}
Send()
{
if( !this.Hostname ) throw new Error( "Url not set" );
2016-03-21 17:16:24 +00:00
var req = ( this.Secured ? https : http )
2016-02-11 00:16:16 +00:00
.request( this.Options, this.OnResponseReceived.bind( this ) );
req.end( this.RawPostData );
}
get Options()
{
return {
hostname: this.Hostname
, port: this.Port
, path: this.Path
, method: this.Method
, headers: this.Headers
};
}
OnResponseReceived( Response )
{
2016-02-11 16:16:08 +00:00
var _self = this;
var ResponseData = new Buffer( 0 );
Response.addListener( "data",
Data => ResponseData = Buffer.concat([ ResponseData, Data ])
);
Response.addListener( "end", () => {
_self.emit( "RequestComplete"
2016-02-28 21:46:29 +00:00
, this, new HttpRequestCompleteEventArgs( Response, ResponseData )
2016-02-11 16:16:08 +00:00
);
} );
2016-02-11 00:16:16 +00:00
}
}
HttpRequest.HttpRequestCompleteEventArgs = HttpRequestCompleteEventArgs;
module.exports = HttpRequest;