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

如何用AutoHotKey V2创建POST请求与REST API请求?求实用工具脚本

AutoHotKey V2 实现 POST 请求与 REST API 调用

基础POST请求(表单格式)

直接用系统自带的WinHttp.WinHttpRequest组件就能实现,无需额外依赖:

; 发送表单格式的POST请求
PostForm(url, formData) {
    whr := ComObject("WinHttp.WinHttpRequest.5.1")
    whr.Open("POST", url, false)
    whr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
    try {
        whr.Send(formData)
        return whr.ResponseText
    } catch e {
        return "请求失败: " e.Message
    }
}

; 调用示例
response := PostForm("https://example.com/api/login", "username=test&password=123456")
MsgBox(response)

REST API POST请求(JSON格式)

REST接口常用JSON传参,AHK V2自带JsonSerialize和JsonParse函数处理JSON数据:

; 发送JSON格式的REST POST请求
PostJson(url, dataObj) {
    whr := ComObject("WinHttp.WinHttpRequest.5.1")
    whr.Open("POST", url, false)
    whr.SetRequestHeader("Content-Type", "application/json")
    ; 将AHK对象转为JSON字符串
    jsonStr := JsonSerialize(dataObj)
    try {
        whr.Send(jsonStr)
        ; 将响应JSON转回AHK对象(按需使用)
        return JsonParse(whr.ResponseText)
    } catch e {
        return "请求失败: " e.Message
    }
}

; 调用示例
userInfo := {name: "李四", age: 30, email: "lisi@example.com"}
result := PostJson("https://example.com/api/user/create", userInfo)
if !IsObject(result)
    MsgBox(result)
else
    MsgBox("创建成功,用户ID: " result.userId)

简化流程的通用工具脚本

写一个通用HTTP请求函数,支持POST、GET等方法,自动处理不同数据格式,后续调用更省心:

; 通用HTTP请求工具
HttpReq(method, url, data := "", headers := {}) {
    whr := ComObject("WinHttp.WinHttpRequest.5.1")
    whr.Open(method, url, false)
    ; 设置自定义请求头
    for key, val in headers
        whr.SetRequestHeader(key, val)
    try {
        whr.Send(data)
        return {
            status: whr.Status,
            statusText: whr.StatusText,
            rawText: whr.ResponseText,
            json: whr.ResponseText ? JsonParse(whr.ResponseText) : ""
        }
    } catch e {
        return {error: true, msg: e.Message}
    }
}

; 简化调用示例
; 1. 表单POST
formResp := HttpReq("POST", "https://example.com/api/submit", "name=张三&phone=13800138000", {"Content-Type": "application/x-www-form-urlencoded"})
if formResp.error
    MsgBox(formResp.msg)
else
    MsgBox("提交结果: " formResp.rawText)

; 2. JSON格式REST请求
jsonResp := HttpReq("POST", "https://example.com/api/article", JsonSerialize({title: "AHK V2 教程", content: "通用HTTP请求函数"}), {"Content-Type": "application/json"})
if jsonResp.error
    MsgBox(jsonResp.msg)
else
    MsgBox("文章创建成功,ID: " jsonResp.json.articleId)

注意事项

  • 确保使用AutoHotKey V2.0.0及以上版本,JSON相关函数是V2新增的;
  • 若遇到HTTPS证书验证问题,可添加whr.SetOption(4, 13056)跳过验证(仅测试环境使用)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:43:13