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

使用TRESTClient下载文件时遭遇Unicode编码映射异常求助

解决TRESTClient下载文件时的Unicode编码映射异常问题

问题原因

异常提示「No mapping for unicode character exists in target multi-byte code page」,是因为TRESTClient默认使用系统多字节编码解析响应头(尤其是Content-Disposition中的UTF-8文件名),当文件名包含系统编码无法映射的Unicode字符时触发错误。

解决方案

方案1:强制设置响应编码为UTF-8

在执行请求前,明确指定RESTClient的默认响应编码为UTF-8,确保解析响应头和内容时使用正确编码:

var
  RESTClient1: TRESTClient;
  RESTRequest1: TRESTRequest;

RESTClient1 := TRESTClient.Create(myUrl);
RESTClient1.DefaultResponseEncoding := TEncoding.UTF8; // 关键设置
RESTRequest1 := TRESTRequest.Create(RESTClient1);
RESTRequest1.AddAuthParameter('Authorization', 'Bearer ' + mySessionId, pkHTTPHEADER, [poDoNotEncode]);
RESTRequest1.AddParameter('Accept', 'application/octet-stream', pkHTTPHEADER, [poDoNotEncode]);
RESTRequest1.Execute;

if RESTRequest1.Response.StatusCode <> 200 then
begin
  // 抛出异常逻辑
end;

result := RESTRequest1.Response.RawBytes;

方案2:禁用自动内容类型解析,直接处理二进制数据

如果不需要解析响应文本,仅需获取原始字节流,可以关闭TRESTRequest的自动内容类型识别,避免编码转换操作:

var
  RESTClient1: TRESTClient;
  RESTRequest1: TRESTRequest;

RESTClient1 := TRESTClient.Create(myUrl);
RESTRequest1 := TRESTRequest.Create(RESTClient1);
RESTRequest1.Options := RESTRequest1.Options + [roNoAutoContentType]; // 禁用自动类型解析
RESTRequest1.AddAuthParameter('Authorization', 'Bearer ' + mySessionId, pkHTTPHEADER, [poDoNotEncode]);
RESTRequest1.AddParameter('Accept', 'application/octet-stream', pkHTTPHEADER, [poDoNotEncode]);
RESTRequest1.Execute;

if RESTRequest1.Response.StatusCode <> 200 then
begin
  // 抛出异常逻辑
end;

result := RESTRequest1.Response.RawBytes;

方案3:调整Accept头匹配实际响应类型

既然Fiddler确认响应是text/plain,可以将Accept头改为text/plain; charset=utf-8,明确告知服务器返回UTF-8编码的文本,同时让TRESTClient用对应编码解析:

RESTRequest1.AddParameter('Accept', 'text/plain; charset=utf-8', pkHTTPHEADER, [poDoNotEncode]);

补充说明

  • 优先尝试方案1或方案2,因为你最终需要的是RawBytes,避免不必要的编码转换能从根源上解决问题。
  • 如果需要提取文件名,注意手动解析Content-Disposition头,使用UTF-8解码URL编码的文件名部分(比如my%20%28filename%29.TXT解码为my (filename).TXT)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 19:42:22