Search code examples
jsongame-maker

GameMaker runner crashes when making HTTP requests


I recently got back into using GameMaker:Studio, and hoo boy have there been some massive updates since I last used it! In fact the last time I used it they only had Windows and HTML5 as export options...

Anyway, eager to try out some of the new stuff, I decided to take a shot at the native HTTP functions, since they looked very promising.

I did a test using http_post_string() to great effect, sending a JSON string to my server and getting a JSON string back. The returned string actually represented an object with a single property, "echo", which contained the HTTP request that had been made, just to see what GM:S was sending.

I didn't like that it sent Content-Type: application/x-www-form-urlencoded when it was quite clearly JSON, and I wanted the ability to set my own User Agent string so that the server could know which game was talking to it without having to pass an extra parameter.

So I re-created the same request using the lower-level http_request() function. Everything looked fine, so I tested it.

It crashed. Like, no error messages or anything, just a total crash and Windows had to force-close it.

So here I am with code that by all rights should work fine, but crashes when run...

///send_request(file,ds_map_data,callback_event_id)
var request = ds_map_create();
request[? "instance"] = id;
request[? "event"] = argument2;

if( !instance_exists(obj_ajax_callback)) {
    instance_create(0,0,obj_ajax_callback);
}

var payload = json_encode(argument1);
var headers = ds_map_create();
headers[? "Content-Length"] = string_length(payload);
headers[? "Content-Type"] = "application/json";
headers[? "User-Agent"] = obj_ajax_callback.uastring;

var xhr = http_request("https://example.com/"+argument0,"POST",headers,payload);

with(obj_ajax_callback) {
    active_callbacks[? xhr] = request;
}

ds_map_destroy(headers);

obj_ajax_callback is an object that maintains a ds_map of active requests, and in its HTTP event it listens for those requests' callbacks and reacts along the lines of with(request[? "instance"]) event_user(request[? "event"]) so that the calling object can handle the response. This hasn't changed from the fully working http_post_string() attempt.

Any idea what could be causing this crash?


Solution

  • The reason why this crashes is because you are sending the Content-Length header as a real instead of a string. If you change your line to

    headers[? "Content-Length"] = string(string_length(payload));
    

    It should work.