马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?站点注册
×
本帖最后由 pbai 于 2026-11-20 06:17 编辑
PBIDEA:用 uo_curl 做 HTTP 客户端全解(15 个动词、表单上传、多线程下载队列与进度回调的真实边界,PB10 基准 · PB12.5 实测)
阅读说明
1. 适用版本:基准版本 PB10;兼容/实测:PB 12.5(PBIDEA 1.x,本文以 2026-10-10 导出的 websuite.pbl 源码为准)。
2. 支持数据库:本文不涉及数据库。
3. 操作系统与环境要求:Windows 7 及以上;需已安装 PBIDEA 运行库(核心动态库及其依赖),uo_curl 依赖的 libcurl 已随运行库内置;http 与 https 均可(https 需系统根证书)。
4. 难度系数:★★★☆☆(需要一点 HTTP 常识:方法、头、表单、状态码;示例可直接跑)。
5. 其它阅读说明:本文所有读数来自本机自建的对端(一个 Python 小 HTTP 服务),因此「服务端看到什么」都是实测回显,不是推断。示例默认用 127.0.0.1:18080 作为对端,把它换成你自己的地址即可。想先看 uo_json 的路径写法,可配合《用 uo_json 的 set/get 与路径语法操作 JSON》一起读。
一、uo_curl 到底是什么
PBIDEA 里能发 HTTP 请求的对象不止一个。uo_httpclient 是一个自研的轻封装,方法少、够用;uo_curl 则是直接把 libcurl 包了一层——它的方法名、参数、默认行为基本是 libcurl 的直译,能力上限也基本等于 libcurl。
判断依据写在源码里:uo_curl 的所有方法都指向 PBIDEA 运行库中 curl* 开头的导出(curlCreate、curlSetUrl、curlRequest、curlSetForm、curlDownloadFile…),类注释就是「基于curl库的 httpclient」。而它的默认 User-Agent 更直接:请求不带 UA 时,服务端收到的头是 pbidea httpclient(libcurl) 1.0(实测)。
两者的分工,一句话:
- 要做一个「够用的接口调用」:uo_httpclient 更省事,DownLoad 一把梭,返回值直接是响应文本。
- 要控制细节:15 个 HTTP 动词、multipart 上传、下载到文件、多线程分段下载、进度回调、代理类型、HTTP 版本、证书与私钥、JWT、Cookie 文件——这些都只有 uo_curl 有。
uo_curl 是非可视对象(from nonvisualobject),create uo_curl 即可,不需要窗口。
二、五分钟上手:三步
uo_curl 的调用模型是三段式:准备(Set 系列)→ 发起(request)→ 读结果(response)。下面这段是最小可运行版本。
前置:global type 里已有 uo_curl(PBIDEA 的 websuite.pbl 已提供,无需自己建)。
步骤:1) 新建一个 Standard Function 或在按钮 clicked 里贴入代码;2) 把 ls_url 换成你能访问的地址;3) 运行,MessageBox 会显示状态码与正文长度。 - // 示例输入:目标地址(换成你的接口)
- string ls_url
- ls_url = 'http://127.0.0.1:18080/hello'
- uo_curl lc
- boolean lb
- string ls_body
- long ll_code
- lc = create uo_curl
- lb = lc.request(lc.HttpGet, ls_url)
- ll_code = lc.response.httpcode
- // 正文一定要从 response.data 取,response.text 实测恒为空(见第四节)
- ls_body = lc.FromUTF8(lc.response.data)
- destroy lc
- MessageBox('GET 结果', 'ret=' + string(lb) + ' code=' + string(ll_code) + ' bytes=' + string(Len(ls_body)) + '~r~n' + ls_body)
复制代码
实测输出:ret=true code=200 bytes=21,正文 hello-from-local-peer。
三个要注意的点,都是实测出来的:
- request() 返回的 Boolean 只表示「这次调用有没有正常完成」,不表示业务成功。404 也返回 true(实测)。
- 读结果一律用 lc.response.xxx,response 是 uo_curl 的实例变量(类型 uo_response),不用自己 create。
- lc.HttpGet 这些常量挂在对象上,所以可以用实例去点(lc.HttpGet),不要写成裸的 HttpGet(在别的对象里会报未定义)。
三、request 的重载与 15 个动词常量
request 有 8 个重载,本质是两种写法 × 四种体:
- // 写法一:先 SetUrl(方法可在字符串里给),再 request
- subroutine SetUrl(readonly string url, readonly string method) // 'GET' 'POST' ...
- subroutine SetUrl(readonly string url, int method) // 常量形态
- // 写法二:一次给全(最常用)
- function boolean request(int nHttpType, readonly string strUrl)
- function boolean request(int nHttpType, readonly string strUrl, readonly string data)
- function boolean request(int nHttpType, readonly string strUrl, readonly blob data)
- function boolean request(int nHttpType, readonly string strUrl, readonly uo_json data)
- // 以及不带 url 的四个同名重载,配合 SetUrl 使用
复制代码
动词常量(uo_curl 的 type variables 里定义的,共 15 个):
| 常量 | 值 | 常量 | 值 | 常量 | 值 | | HttpGet | 1 | HttpCopy | 6 | HttpPurge | 11 | | HttpPost | 2 | HttpHead | 7 | HttpLock | 12 | | HttpPut | 3 | HttpOptions | 8 | HttpUnlock | 13 | | HttpPatch | 4 | HttpLink | 9 | HttpPropfind | 14 | | HttpDelete | 5 | HttpUplink | 10 | HttpView | 15 |
PUT / DELETE 实测都能正常发(对端回显 method=PUT len=...、method=DELETE)。HEAD 是个例外:本机对端支持 HEAD,但 request(lc.HttpHead, ...) 实测回来的是 httpcode=0、verb=''、data 空——拿不到响应头。要判断资源是否存在,请用 GET 看 httpcode,别指望 HEAD。
四、响应对象 uo_response:字段全表,以及三个必须知道的坑
uo_response 的成员(源码顺序):header、headerlist(string 数组)、data、errcode、errtext、httpcode、verb、timeout、charset、ContentType、Server、text、json、xml、headers。
实测下来「填得上」的只有这几个:
| 字段 | 类型 | 实测表现 | | httpcode | int | 200 / 302 / 401 / 404 都正确 | | verb | string | 请求方法回显,GET 时是 'GET' | | data | blob | 正文原始字节,唯一可靠的取正文入口 | | ContentType | string | 如 text/plain; charset=utf-8 | | charset | string | 从 Content-Type 里提出来的编码名,如 utf-8 / gbk | | Server | string | 对端 Server 头 | | json | uo_json | Content-Type 为 application/json 时已自动解析好 | | headers | uo_json | 全部响应头,键值对(见下) | | header | string | 只有状态行那 25 个字符,不是完整头 | | headerlist(string 数组) | string 数组 | 实测为空,UpperBound = 0 | | text | string | 实测恒为空(四种 Content-Type 都试过) | | errtext | string | 成功时是 'ok',失败时也是 'ok'(见第十节) |
坑一:response.text 恒为空
同一份响应,datalen=21 而 textlen=0:正文在 data 里,text 是空的。四种响应都验证过——text/plain; charset=utf-8、application/json、text/html; charset=utf-8、text/plain; charset=gbk,text 一律为空。开 SetUtf8(true) 也不改变这一点。
所以「取正文」这件事必须自己动手。
坑二:String(data) 直接转是乱码
data 是 blob,很多人第一反应是 String(lc.response.data)。本机实测这条必错:
- // 实测:21 字节的 hello-from-local-peer 转出来是成对的怪字符
- ls1 = String(lc.response.data) // 乱
- ls2 = String(lc.response.data, EncodingUTF8!) // 对
- ls3 = lc.FromUTF8(lc.response.data) // 对
复制代码
原因不在 uo_curl,而在 blob 与 string 的默认互转:本机 PB 把裸 blob 当 UTF-16LE 成对解释,ASCII 的 hello 被两两拼成了「敨汬」这类字符。正确写法只有两条:
- String(blob, encoding):显式给编码,UTF-8 用 EncodingUTF8!(PB10 与 PB12.5 实测都支持);
- lc.FromUTF8(blob):uo_curl 自带的工具方法。
两个都试过,UTF-8 中文页 中文正文-UTF8 两边读出来完全一致。反过来,要把字符串变成 UTF-8 的 blob 发给服务端,用 lc.ToUTF8(string)。
至于 GBK 的响应(charset=gbk),FromUTF8 会把非 ASCII 全变问号(实测 ????GBK),这时应当用 String(data, EncodingANSI!) 或先转码——charset 字段只是「对端说的编码」,不会自动帮你转。
坑三:headerlist 空,但 headers 是全的
headerlist 这个数组实测为空,header 只有状态行。要读具体某个响应头,用 headers:
- // headers 是一个 uo_json,toString 出来就是可读的键值对
- MessageBox('响应头', lc.response.headers.tostring())
复制代码
实测输出(节选):{"Content-Length":"58","Content-Type":"application/json; charset=utf-8","Charset":"utf-8","Date":"...","HTTP/1.1 200 OK":"","Server":"BaseHTTP/0.6 Python/3.13.14", ...}。
注意里面那个 "HTTP/1.1 200 OK":"" 的伪键——它是状态行被塞成了一个空值键,遍历头的时候记得跳过它。uo_response 源码注释也提醒:这些成员名是对象内部用的,改了就失效,所以不要自己另写一个同名类去接。
json 这个字段是白送的
当响应 Content-Type 是 application/json 时,response.json 已经解析好了,直接用 GetString / GetLong / GetType 取值即可,不用再 Parse 一遍:
- // 对端返回:code=0 / name=pbai / num=42 / tags 是两个元素的数组
- ls_name = lc.response.json.GetString('/name') // 'pbai'
- ll_num = lc.response.json.GetLong('/num') // 42
- ls_type = lc.response.json.GetType('/num') // 'number'
复制代码
GetString(key) 与 GetLong(key) 是单参直取的重载,最省事。要一次取多种类型、还要知道取没取到,才用 ref 形态的 Get(key, ref value)(返回 Boolean);本机实测 Get('/name', ls_var) 在编译期就报 C0084: Bad number of arguments,而 GetString/GetLong/GetType 一路通过——别跟重载较劲,按类型选 GetXxx。
五、请求头与参数
SetHeader:两个重载
- subroutine SetHeader(readonly string strKey, readonly string strValue)
- subroutine SetHeader(readonly uo_map headers)
复制代码
单键版和批量版可以混用。实测把 X-From: pb103 加上去,服务端确实收到了(对端回显 xf=pb103)。
- // 逐个加 + 用 uo_map 批量加,两种写法等价
- uo_map lm
- lm = create uo_map
- lm.set('X-A', '1')
- lm.set('X-B', '2')
- lc.SetHeader(lm)
- lc.SetHeader('X-From', 'pb103')
- destroy lm
复制代码
SetParam:三个重载,但只在 GET 上有效
- subroutine SetParam(readonly string strKey, readonly string strValue)
- subroutine SetParam(readonly string strKey, readonly string strValue, boolean urlencode)
- subroutine SetParam(readonly uo_map params)
复制代码
实测(GET):SetParam('a','1') + SetParam('b','x y', true),对端看到的路径是 path=/echo?a=1&b=x%20y——自动拼到 query string,第三参 true 时做 URL 编码(空格变 %20)。
实测(POST):同样两个参数,request(HttpPost, ...) 之后服务端收到的请求体长度为 0(参数没有进 body)。所以 POST 传参不要用 SetParam 想当然,老老实实用 SetForm(第七节)或 SetBody。
六、请求体:SetBody 三种形态
- subroutine SetBody(readonly string data)
- subroutine SetBody(readonly blob data)
- subroutine SetBody(readonly uo_json data)
复制代码
SetBody 配合 SetUrl + 无参 request() 使用,是最灵活的写法(尤其当请求体是算出来的):
- // 两步式:先定地址与方法,再挂体,最后发
- lc.SetUrl('http://127.0.0.1:18080/echo', lc.HttpPost)
- lc.SetBody(blob('RAWBODY-123'))
- lc.request()
复制代码
实测:服务端回显 method=POST ctype=application/x-www-form-urlencoded len=... head=RAWBODY-123,体确实送到了。
这里有个容易踩的地方:blob('RAWBODY-123') 是把字符串按本机默认编码转成 blob 的,如果你要的是 UTF-8 字节流,用 lc.ToUTF8('...') 显式转,否则中文会以本机 ANSI 字节发出去,对端按 UTF-8 解就是乱码。
七、表单上传:SetForm 四个重载
- subroutine SetForm(readonly string strKey, readonly string strValue)
- subroutine SetForm(readonly string strKey, readonly string strFile, boolean IsFile)
- subroutine SetForm(readonly string strKey, readonly string strFile, boolean IsFile, readonly string contentType)
- subroutine SetForm(readonly string strKey, readonly blob data)
复制代码
四个重载覆盖了 multipart 的四种字段:普通文本字段、磁盘文件、带 MIME 类型的文件、内存里的二进制。实测三种都到达了服务端:字段名 f1(文本)、f2(blob)、f3(文件,IsFile = true)都对端回显正确。
关键一点:SetForm 走的是 multipart/form-data,不是 application/x-www-form-urlencoded。 实测服务端收到的 Content-Type 是 multipart/form-data; boundary=------------------------59a36279a4de0e01,boundary 由库里自动生成,两个字段 240 字节。所以对端必须按 multipart 解析——用 PHP 的 $_FILES/$_POST、Java 的 getPart、Python 的 cgi.FieldStorage 都没问题,但别用「读原始 body 再按 a=1&b=2 拆」的方式接,那样只能拆出 boundary 噪音。
顺带把三个输入形态的 Content-Type 归一下,免得混:
| 送体方式 | 服务端看到的 Content-Type | | request(method, url, 字符串) / SetBody(字符串) | application/x-www-form-urlencoded | | SetForm(...)(任意重载) | multipart/form-data; boundary=... | | SetBody(blob) / SetBody(uo_json) | 不自动设,按你 SetHeader 的来 |
前置:本机先准备一个要上传的文件(示例用 up103.txt)。
步骤:1) 把 ls_file 指到你自己的文件;2) 运行;3) 看服务端返回的字段清单与总字节数。 - // 示例输入:要上传的本地文件
- string ls_file
- ls_file = 'up103.txt'
- // 示例输入:目标上传接口
- string ls_url
- ls_url = 'http://127.0.0.1:18080/upload'
- uo_curl lc
- lc = create uo_curl
- lc.SetForm('user', 'pbai') // 普通文本字段
- lc.SetForm('file1', ls_file, true) // 磁盘文件字段(第三参 true 才是文件)
- lc.request(lc.HttpPost, ls_url)
- MessageBox('上传结果', 'code=' + string(lc.response.httpcode) + '~r~n' + lc.FromUTF8(lc.response.data))
- destroy lc
复制代码
一个常见误区:SetForm('k', 'v') 与 SetForm('k', 'v', false) 不是一回事——两参版是文本字段,三参版第三参 false 是「按文件名字符串当值」,只有 true 才会去读磁盘。
八、下载:三条路,各有各的取舍
路线一:SetDownloadFile(最简单)
- lc.SetDownloadFile('dl103.bin') // 之后这个实例的响应体直接落到文件
- lc.request(lc.HttpGet, 'http://127.0.0.1:18080/file?n=20000')
复制代码
实测:文件 20000 字节落盘,而 response.data 的长度是 0——一旦设了下载文件,正文就不再往 data 里攒。所以「又想存文件又想拿内存副本」是做不到的,需要两份就请求两次,或者用 SetResponseStream 自己接。
路线二:SetResponseStream(要自己接流时)
- function boolean SetResponseStream(uo_stream stream)
复制代码
把响应字节灌进一个 uo_stream,适合「边下边算摘要」这类场景。返回值是 Boolean,失败时返回 false。
路线三:DownloadFile 的多线程队列(大文件用这个)
- function ulong DownloadFile(readonly string url, readonly string fileName)
- function ulong DownloadFile(readonly string url, readonly string fileName, int threadCount, boolean enabledProgress)
- subroutine WaitDownloadFile(boolean messageloop)
- subroutine StopDownloadFile()
复制代码
这是 uo_curl 里唯一「像下载工具」的功能:一个文件切成多段、每段一个线程,默认 4 线程,返回一个队列号。实测下 200000 字节:
- // 示例输入:下载地址与落地文件
- string ls_url
- ls_url = 'http://127.0.0.1:18080/file?n=200000'
- string ls_file
- ls_file = 'dl_queue.bin'
- uo_curl lc
- ulong lu_id
- lc = create uo_curl
- lu_id = lc.DownloadFile(ls_url, ls_file, 4, false) // 4 线程,不启用进度
- lc.WaitDownloadFile(false) // 等队列跑完(false = 不泵消息)
- MessageBox('队列下载', 'id=' + string(lu_id) + ' bytes=' + string(FileLength(ls_file)))
- destroy lc
复制代码
实测:id=1,文件 200000 字节,md5 与「完整 200000 字节全 A」的期望值一致(7f11a7875a8f…)——分段下载拼回来的字节是对的,没有错位或截断。WaitDownloadFile(true) 会边等边泵消息(窗口里用这个,别让界面假死);StopDownloadFile() 是「放弃队列里没下完的部分」。
九、进度回调与中止:真实边界
进度是事件,不是回调函数参数——所以要继承 uo_curl 写一个子类,在子类里实现 onprogress:
- event type boolean onprogress (unsignedlong totalsize, unsignedlong downsize, unsignedlong speed, unsignedlong percent)
- event onfinish (boolean success, string info)
- event ondata (blob data)
- event onheader (string key, string value)
- event onprogressthread (unsignedlong id, integer threadid, unsignedlong totalsize, unsignedlong downsize, unsignedlong speed, unsignedlong percent)
- event onfileend (unsignedlong id, string url, string file, longlong size)
- event onfilestart (unsignedlong id, string url, string file, longlong size, integer threadcount)
- event onprogressdown (unsignedlong id, unsignedlong downsize, unsignedlong speed, unsignedlong percent)
复制代码
onprogress 的返回值语义按源码注释是「返回 TRUE 继续下载,返回 FALSE 中止」。实测两种对端、两种结果:
| 场景 | 对端 | 回调次数 | 最后 percent | 结论 | | 快对端 200KB | 立即返回 | 1 次 | 100 | 下载太快,只在结束时回调一次 | | 慢对端 200KB | 每 8KB 停 40ms | 25 次 | 100 | 粒度 = 网络分块,8KB 一次 |
而中止这条路,实测走不通:在 onprogress 里判断 percent >= 30 就 abort() 并 return false,结果文件仍然下满了 200000 字节,后续回调照旧跑到 100。同样的 return false 在 4 线程队列里也没能拦住。
所以正确的心态是:onprogress 当「进度显示器」用,不要当「刹车」用。真要中途停,用 abort()(第十节)+ 立刻 destroy,或者干脆自己用 uo_httpclient 的分段逻辑控制。这一点我按实测写,不做美化——源码注释写的「返回 FALSE 中止」在本机没有生效。
另外两个事件实测不触发:onheader(0 次)与 ondata(0 次)。要读响应头请用 response.headers,要读正文请用 response.data,别指望事件。
十、超时、错误与「errtext 恒为 ok」
超时的两种写法
- subroutine SetTimeout(ulong nTimeout) // 整体:连接 + 传输
- subroutine SetTimeout(ulong connectTimeout, ulong connectAndReadTimeout)
复制代码
实测 SetTimeout(500) 打一个 3 秒才回的对端:ret=false、httpcode=0、errcode=0、errtext 空。两参版 SetTimeout(300, 800) 打慢速流也一样。结论:超时失败时,uo_response 里没有任何可读的错误信息,你只能靠 Boolean 返回 + httpcode=0 判断。
errtext 的真相
这是本文最需要记住的一条:
| 场景 | ret | httpcode | errcode | errtext | | 正常 200 | true | 200 | 0 | ok | | 超时 | false | 0 | 0 | 空 | | 404 | true | 404 | 404 | ok |
也就是说:errtext 不是错误信息,它只在成功链路上写了个 ok。判断成败的正确姿势是三层:
- request() 返回 false → 网络层失败(超时、DNS、连不上),httpcode 必为 0;
- httpcode 不在 2xx → 业务/协议层失败,但请求本身是成功的(ret=true);
- errcode == httpcode,两者一起看即可,不要依赖 errtext。
- // 三层判断的完整写法(可直接放进你自己的工具函数)
- boolean lb_ok
- long ll_code
- string ls_msg
- lb_ok = lc.request(lc.HttpGet, ls_url)
- ll_code = lc.response.httpcode
- if not lb_ok then
- ls_msg = '网络层失败(超时/连不上),httpcode=' + string(ll_code)
- elseif ll_code < 200 or ll_code >= 300 then
- ls_msg = '协议层失败,httpcode=' + string(ll_code)
- else
- ls_msg = '成功,' + string(Len(lc.response.data)) + ' 字节'
- end if
- MessageBox('归并结果', ls_msg)
复制代码
十一、其余开关:重定向、压缩、UA、代理、版本、SetNoBody
| 方法 | 作用 | 实测结论 | | SetForward(boolean) | 是否跟随重定向 | true 时 302 被跟随,最终 httpcode=200;false 时拿到 302 本体 | | SetCompress(boolean) | 加 Accept-Encoding: gzip, deflate, br,并压缩上传数据 | 服务端确实收到 ae=gzip, deflate, br;同一请求的 3 字节体变成 23 字节(压缩后反而更长) | | SetUserAgent(string) | 自定义 UA | 服务端收到 ua=pbai-curl-103;不设时是 pbidea httpclient(libcurl) 1.0 | | SetProxy(ip, port {, proxyType}) | 代理,7 种类型常量 | 代理常量:ProxyHttp=0 / ProxyHttp1_0=1 / ProxyHttps=2 / ProxySocks4=3 / ProxySocks5=4 / ProxySocks5a=5 / ProxySocks4a=6 / ProxySocks5_hostname=7(本文未接代理实测) | | SetVersion(int) | HTTP 版本 | 0=NONE / 1=1.0 / 2=1.1 / 3=2.0 / 4=2TLS / 5=2_PRIOR_KNOWLEDGE / 6=3 / 7=3ONLY(本文未实测协商结果) | | SetNoBody(boolean) | 只要头不要体 | 实测 datalen=0,httpcode 正常 | | SetCookieFile(string) | 指定 cookie 文件 | 本文未实测 | | SetDebug(boolean, file) | 打开 libcurl 调试输出到文件 | 本文未实测 |
SetCompress(true) 那一行值得单独提醒:它不只影响下载,还会把你要上传的体压一遍。对端如果不懂 gzip 解压,收到的就是二进制乱码——这就是上面 3 字节变 23 字节的原因。
十二、认证与证书
- subroutine SetBasicAuth(readonly string username, readonly string password)
- subroutine SetJWTAuth(readonly string token)
- subroutine SetCertInfo(readonly string ca_cert_file, readonly string client_cert_file, readonly string client_cert_type)
- subroutine SetPrivateKeyInfo(readonly string private_key, readonly string private_key_passwd, readonly string private_key_type)
- subroutine SetCert(readonly string cert, readonly string keytype, readonly string password)
复制代码
Basic 认证实测有效:带 SetBasicAuth('pbai','secret') 时对端回 200,不带时回 401(服务端还发了 WWW-Authenticate)。JWT 走的是 Authorization: Bearer(与 uo_jwt 签出来的 token 配套),证书三件套支持 PEM / DER / P12,本文未接 https 双向认证实测。
一个实际经验:SetJWTAuth 的 token 如果含中文或非 ASCII 声明,先 Base64 好再传,别直接把 JSON 塞进去。
十三、复用与异步:Reset、busy、allowasync
- 想复用同一个实例连打多次:中间的 Reset() 是必须的,而且不只是「脏不脏」的问题。实测过一次很典型的翻车:同一个实例先发了两个 GET,第三次调 SetForm + request(HttpPost, ...),服务端收到的竟然是 GET(对端走的是 GET 分支,压根没进 multipart);把 Reset() 加到每次请求前,同一条链立刻恢复正常(method=POST ctype=multipart/form-data len=240)。同一轮里 SetDownloadFile 也出现了「调用返回 code=200、进度回调 26 次,但文件根本没落地(FileLength=-1)」,加 Reset() 后文件正常 200000 字节。结论:一个实例一次请求,请求前先 Reset()。 本文示例对象 nvo_art103 的每个方法第一行都是 Reset(),就是这个原因。
- Reset() 之后复用实测正常:a_len=21、b_len=17 两发都对。
- busy():问「现在是不是还在异步干活」。同步调用返回后实测 busy=false。
- 异步:allowasync 属性默认是 true,注释说「在 post 函数或事件里发起 request 时默认异步」。但在本机无消息循环的探针环境下,request() 是同步返回的(返回时 httpcode 已是 200、busy=false)。要强制同步,SetAsyncRequest(false) 或直接改 lc.allowasync = false。窗口里如果发现「请求发出去了但结果还没回来就往下走了」,先查这个开关。
十四、完整示例:一个 HTTP 小助手
把上面零散的东西收成一个可复用的子类 nvo_art103(from uo_curl,非可视、非 autoinstantiate)。它做了四件事:JSON 接口取值、取正文、表单提交、下载(含进度计数与失败归并)。
前置:1) PBL 中已能引用 PBIDEA 的 websuite.pbl(uo_curl 在其中);2) 新建一个 Non-Visual Object,命名为 nvo_art103,祖先选 uo_curl(不是 nonvisualobject!);3) 把下面代码整体贴进去后 rebuild。
步骤:4) 在任意按钮里 create nvo_art103;5) 调 of_getjson(...) 等方法;6) MessageBox 会打印每步读数。 - // ---- 实例变量 ----
- // long il_prog_hits 进度回调次数
- // long il_last_pct 最后一次回调的百分比
- public function string of_w (string as_name, string as_val);
- return as_name + '=' + as_val + '|'
- end function
- public function string of_getjson (string as_url);
- string ls
- Reset()
- request(HttpGet, as_url)
- ls = of_w('code', string(response.httpcode))
- ls = ls + of_w('name', response.json.GetString('/name'))
- ls = ls + of_w('num', string(response.json.GetLong('/num')))
- ls = ls + of_w('type', response.json.GetType('/num'))
- return ls
- end function
- public function string of_gettext (string as_url);
- string ls
- Reset()
- request(HttpGet, as_url)
- ls = of_w('code', string(response.httpcode))
- ls = ls + of_w('bytes', string(Len(response.data)))
- ls = ls + of_w('txt', FromUTF8(response.data))
- return ls
- end function
- public function string of_postform (string as_url, string as_user, string as_pass);
- string ls
- Reset()
- SetForm('user', as_user)
- SetForm('pass', as_pass)
- request(HttpPost, as_url)
- ls = of_w('code', string(response.httpcode))
- ls = ls + of_w('bytes', string(Len(response.data)))
- return ls
- end function
- public function string of_download (string as_url, string as_file);
- string ls
- il_prog_hits = 0
- il_last_pct = 0
- Reset()
- EnableProgress(true)
- SetDownloadFile(as_file)
- request(HttpGet, as_url)
- ls = of_w('code', string(response.httpcode))
- ls = ls + of_w('file', string(FileLength(as_file)))
- ls = ls + of_w('data', string(Len(response.data)))
- ls = ls + of_w('hits', string(il_prog_hits))
- ls = ls + of_w('pct', string(il_last_pct))
- return ls
- end function
- public function string of_queue (string as_url, string as_file, integer ai_threads);
- ulong lu_id
- string ls
- Reset()
- lu_id = DownloadFile(as_url, as_file, ai_threads, false)
- WaitDownloadFile(false)
- ls = of_w('id', string(lu_id))
- ls = ls + of_w('file', string(FileLength(as_file)))
- return ls
- end function
- // ---- 进度事件(子类必须自己实现)----
- event onprogress;
- il_prog_hits = il_prog_hits + 1
- il_last_pct = percent
- return true
- end event
复制代码
调用侧(实测读数已填在注释里):
- // 示例输入:本地对端(换成你的服务地址)
- string ls_base
- ls_base = 'http://127.0.0.1:18080'
- nvo_art103 lo
- string ls_out
- lo = create nvo_art103
- // JSON 接口:code=200 name=pbai num=42 type=number
- ls_out = lo.of_getjson(ls_base + '/json')
- // 取正文:code=200 bytes=17 txt=中文正文-UTF8
- ls_out = ls_out + '~r~n' + lo.of_gettext(ls_base + '/zh')
- // 表单提交:code=200(对端回显 method=POST ctype=multipart/form-data len=240)
- ls_out = ls_out + '~r~n' + lo.of_postform(ls_base + '/echo', 'pbai', 'p@ss')
- // 下载到文件:code=200 file=200000 data=0 hits=N pct=100
- ls_out = ls_out + '~r~n' + lo.of_download(ls_base + '/file?n=200000', 'art103d.bin')
- // 4 线程队列:id=1 file=200000
- ls_out = ls_out + '~r~n' + lo.of_queue(ls_base + '/file?n=200000', 'art103q.bin', 4)
- destroy lo
- MessageBox('HTTP 小助手', ls_out)
复制代码
十五、坑清单(一张表带走)
| # | 坑 | 对策 | | 1 | response.text 恒为空 | 一律用 response.data | | 2 | String(data) 乱码 | String(data, EncodingUTF8!) 或 FromUTF8(data) | | 3 | headerlist 空、header 只有状态行 | 读 response.headers(uo_json) | | 4 | errtext 恒为 ok,404 也是 | 用 ret + httpcode 三层判断 | | 5 | 超时后 errcode=0、errtext 空 | 只认 ret=false + httpcode=0 | | 6 | POST 用 SetParam 传参无效(体长 0) | 用 SetForm 或 SetBody | | 7 | SetForm(k,v,false) 不是文本字段 | 文本字段用两参版 | | 8 | 设了 SetDownloadFile 后 data 为空 | 需要内存副本就别设下载文件 | | 9 | onprogress 返回 false / abort() 不中止 | 当显示器用,别当刹车 | | 10 | onheader / ondata 不触发 | 用 response.headers / response.data | | 11 | HEAD 拿不到响应头(httpcode=0) | 用 GET 判断存在性 | | 12 | SetCompress(true) 会压缩上传体 | 对端不支持就别开 | | 13 | 复用实例不 Reset():下一次请求会沿用上一次的方法与状态(POST 被打成 GET、SetDownloadFile 不落地) | 每次请求前 Reset() | | 14 | blob('中文') 是本机 ANSI 字节 | 用 lc.ToUTF8() | | 15 | Get('/k', var) 编译报 C0084 | 用 GetString / GetLong / GetType |
十六、PB12.5 差异
未发现差异。 本文 35 个探针与示例对象在 PB10(--pb-version 100)与 PB12.5(--pb-version 125)两轨的读数逐条比对一致,唯一不同的是响应头里的 Date 值(时间本身)。特别确认了三条容易有版本差异的点:
- String(blob, EncodingUTF8!) 两版都能用,输出一致;
- GetString/GetLong/GetType 两版都可用,Get('/k', var) 两版都在编译期报 C0084;
- 进度回调的次数与百分比序列两版一致(快对端 1 次、慢对端 25 次)。
十七、实机验证情况
- PB10:--pb-version 100 编译 0 错误;35 个探针 + 示例对象 nvo_art103 在 PBVM 上运行 全部 PASS,读数与 PB12.5 逐条一致。
- PB12.5:--pb-version 125 编译 0 错误;同上全部 PASS。
- 对端:本机自建 Python HTTP 服务(127.0.0.1:18080),提供 hello / json / zh / gbk / html / 302 / 401 / 404 / 定长二进制 / 慢速流 / multipart 回显 等端点,所有「服务端看到什么」均为其回显,非推断。
- 未实测部分已逐条标注:代理、HTTP 版本协商、Cookie 文件、Debug 输出、https 双向认证、SetResponseStream。这些是按源码签名整理的用法,未做运行级验证。
- 示例对象 nvo_art103 双轨读数(逐条一致):JSON 取值 code=200 name=pbai num=42 type=number;取正文 bytes=17 txt=中文正文-UTF8;表单提交 code=200(对端 method=POST ctype=multipart/form-data len=240);下载 code=200 file=200000 data=0 hits=25 pct=100 total=200000;4 线程队列 id=1 file=200000 busy=false;超时归并 ret=false code=0 errcode=0。
- 交付包内附 tests/t_art103.pbtest,读者可自行复验示例对象的六个方法。
|