HTTPRequest example

Here's a simple example of using the new HTTPRequest object added in 13.6.2.

It opens a dialog and launches three asynchronous requests for images, and displays them when received.

Example button:
HTTP Example.dcf (3.3 KB)

Script:

function OnClick(clickData)
{
	var Dlg = DOpus.Dlg;
	Dlg.window = clickData.func.sourcetab;
	Dlg.template = "testdlg";
	Dlg.detach = true;
	Dlg.Show();

	var Reqs = {};
	for (var i = 0; i < 3; i++)
	{
		var newReq = Dlg.NewHTTPReq();
		newReq.SendRequest("https://www.gpsoft.com.au/assets/img/product-screen-" + (i + 1) + ".jpg");
		Reqs[newReq.id] = { req: newReq, ctrl: "static" + (i + 1) };
	}

	while (true)
	{
	    var Msg = Dlg.GetMsg();
    	if (!Msg.result) break;

		if (Msg.event == "http" && Msg.value == "data")
		{
			var Req = Reqs[Msg.control];
			if (!Req.req.complete)
			{
				var reqData = Req.req.ReadResponse();
				if (DOpus.TypeOf(reqData) == "object.Image")
					Dlg.Control(Req.ctrl).title = reqData;
				Req.req.shutdown();
			}
		}
	}
}
```
7 Likes

Again many thanks for including this.
A few questions after playing with HTTPRequest a bit, but using POST:

  1. Before , I used HTTPRequest (via ActiveX) with a structure like this as the data to send:

    req.Open('POST', endpoint, false);
    var data = JSON.stringify({
    	model: "model1",
    	prompt: "Some prompt",
    	options: {optionA:"valueA",optionB:"valueB"},
    	stream: false
    });
    req.Send(data);
    

    What would be the equivalent with the new HTTPRequest?
    I tried:

    var data = DOpus.Create.Map(
    	"model", "model1",
    	"prompt", "Some prompt",
    	"options", {optionA:"valueA",optionB:"valueB"},
    	"stream", false
    );
    req.AddPostData(data);
    req.SendRequest(endpoint);
    

    but right after sending, status property for req is set to error.

  2. Once the send is performed with SendRequest(), should shutdown() stop the http event or is there another way?
    I tried something like this (just the loop for the dialog) :

    while (true) {
    	msg = dlg.main.GetMsg();
    	if (!msg.result) break;
    	if (msg.event === 'http') { 
    		status = msg.value;
    		Log(1, '=> status : ' + status);
    		//prints "=> status : error"
    		if (status == 'error') {
    			Log(1, 'error code : ' + xhr.errorcode + '\terror : ' + xhr.errortext);
    			//prints "error code : 7	error : Error sending request (10054)"
    			req.shutdown();
    		}
    		else if (status == 'data') { //status is complete with data
    			//process the response
    		}
    	}
    	...
    

    But after shutdown() is executed, the event for http keeps triggering and gives an error in xhr.errorcode, since many properties/methods are no longer avaialble.
    (msg.value is still set to error)

As in the example, you should check the complete property before using any other methods or properties if you're calling Shutdown(). Messages could still be in the message queue even after the request is terminated.