BotanSS/net/HttpRequest.js

108 lines
2.1 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" );
2016-06-16 07:16:29 +00:00
var CompleteEventArgs = require( "./events/HttpRequestComplete" );
2016-02-11 00:16:16 +00:00
class HttpRequest extends EventEmitter
{
constructor( Url, Headers )
{
super();
this.Secured = false;
2016-02-11 00:16:16 +00:00
this.SetUrl( Url );
this.Method = "GET";
this.Headers = Headers || {
"User-Agent": "BotanSS HttpRequest"
};
}
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";
2016-09-08 03:23:57 +00:00
this.RawPostData = Data == undefined ? new Buffer([]) : new Buffer( Data );
2016-02-11 00:16:16 +00:00
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 ) );
2016-06-12 05:45:17 +00:00
req.addListener( "error", ( err ) => {
2016-06-16 07:16:29 +00:00
this.emit( "RequestComplete", this, new CompleteEventArgs( err ) )
2016-06-12 05:45:17 +00:00
} );
2016-02-11 00:16:16 +00:00
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 ResponseData = new Buffer( 0 );
Response.addListener( "data",
Data => ResponseData = Buffer.concat([ ResponseData, Data ])
);
Response.addListener( "end", () => {
2016-06-12 05:45:17 +00:00
this.emit( "RequestComplete"
2016-06-16 07:16:29 +00:00
, this, new CompleteEventArgs( Response, ResponseData )
2016-02-11 16:16:08 +00:00
);
} );
2016-02-11 00:16:16 +00:00
}
}
2016-06-16 07:16:29 +00:00
HttpRequest.HttpRequestCompleteEventArgs = CompleteEventArgs;
2016-02-11 00:16:16 +00:00
module.exports = HttpRequest;