You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GameMaker Studio 1.4.9调用词典API时HTTP请求返回空数据问题

问题描述

在GameMaker Studio 1.4.9中实现词典API信息拉取功能时,所有请求返回空结果,无法绕过服务端拦截规则,无法定位故障点。预期按下空格键触发请求后,弹窗展示查询单词test,实际始终拿到空返回。

现有实现代码

Step Event

if(keyboard_check_pressed(vk_space)){
http_get("https://api.dictionaryapi.dev/api/v2/entries/en/test");
}

HTTP 异步事件

var requestResult = ds_map_find_value(async_load, "result");

var resultMap = json_decode(requestResult);

if(resultMap == -1) 
{
show_message("Invalid result");
exit;
}

if(ds_map_exists(resultMap,"word")){
    var name= ds_map_find_value(resultMap, "word"); 
    show_message("The word name is "+name);
}
故障原因

两个核心问题导致功能异常:

  1. GMS1.4原生http_get方法默认请求头携带的User-Agent带有GameMaker标识,会被目标API的WAF规则直接拦截,返回空内容或403状态码。
  2. 目标词典API的返回结构为条目数组,并非顶层JSON对象,原有代码直接在json_decode返回的顶层结构中查找word字段,逻辑完全不匹配返回格式,即使请求成功也拿不到对应值。
修复方案
  • 替换http_get为http_request方法,自定义请求头携带常规浏览器User-Agent,绕过WAF拦截。
  • 在HTTP事件中优先校验HTTP状态码,确认请求成功后再做内容解析,提前排除请求层面的故障。
  • 修正JSON解析逻辑,先读取返回数组的第一个条目对象,再从对象中提取word字段,解析完成后手动销毁生成的DS结构避免内存泄漏。

修正后Step Event代码

// 构造自定义请求头
var req_headers = ds_map_create();
ds_map_add(req_headers, "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");

if(keyboard_check_pressed(vk_space)){
    // 发送带自定义头的GET请求
    http_request("https://api.dictionaryapi.dev/api/v2/entries/en/test", "GET", req_headers, "");
}

ds_map_destroy(req_headers);

修正后HTTP异步事件代码

// 优先校验请求状态
var http_status = ds_map_find_value(async_load, "http_status");
if(http_status != 200){
    show_message("请求失败,状态码:" + string(http_status));
    exit;
}

var resp_content = ds_map_find_value(async_load, "result");
// 校验返回内容非空
if(resp_content == "" || is_undefined(resp_content)){
    show_message("返回内容为空");
    exit;
}

var parsed_res = json_decode(resp_content);
if(parsed_res == -1){
    show_message("JSON格式解析失败");
    exit;
}

// 识别返回结构为数组(ds_list),取第一个元素
if(ds_exists(parsed_res, ds_type_list)){
    var first_entry = ds_list_find_value(parsed_res, 0);
    if(ds_exists(first_entry, ds_type_map) && ds_map_exists(first_entry, "word")){
        var target_word = ds_map_find_value(first_entry, "word");
        show_message("The word name is " + target_word);
    }
    // 销毁DS结构,防止内存泄漏
    ds_list_destroy(parsed_res);
}

注意:GMS1.4的json_decode方法解析JSON数组时会返回ds_list类型索引,解析JSON对象时返回ds_map类型索引,对接第三方API前需要先确认接口返回的顶层结构类型,不要默认按对象处理。

内容的提问来源于stack exchange,提问作者Empty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 21:24:21