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

Delphi TRESTClient请求中特殊字符显示异常问题求助

Delphi TRESTClient 特殊字符(ä/ö/ü)发送乱码解决方法

问题根源

虽然你已经在请求头中设置了Content-Type: application/json; charset=utf-8,但直接传递Delphi默认的Unicode字符串作为RequestBody时,TRESTRequest会使用系统默认编码(通常是ANSI)对字符串进行编码,导致UTF-8特殊字符丢失,最终显示为�。

修复方案

方案1:使用UTF-8编码的TStringStream传递Body

将字符串转换为UTF-8编码的字节流,再通过AddBody方法传递,确保编码与请求头声明一致:

var
  RESTClient1: TRESTClient;
  RESTRequest1: TRESTRequest;
  lBody: string;
  lStream: TStringStream;

lBody := '{"value": "testäöü"}';
RESTClient1 := TRESTClient.Create(myUrl);
try
  RESTRequest1 := TRESTRequest.Create(RESTClient1);
  try
    RESTRequest1.Method := TRESTRequestMethod.rmPUT;
    RESTRequest1.AddAuthParameter('Authorization', 'Bearer ' + mySessionId, pkHTTPHEADER, [poDoNotEncode]);
    RESTRequest1.AddParameter('Content-Type', 'application/json; charset=utf-8', pkHTTPHEADER, [poDoNotEncode]);
    
    // 创建UTF-8编码的字符串流
    lStream := TStringStream.Create(lBody, TEncoding.UTF8);
    try
      RESTRequest1.AddBody(lStream, ctAPPLICATION_JSON);
      RESTRequest1.Execute;
    finally
      lStream.Free;
    end;

    if RESTRequest1.Response.StatusCode <> 200 then
    begin
      // 处理请求失败逻辑
    end;
  finally
    RESTRequest1.Free;
  end;
finally
  RESTClient1.Free;
end;

方案2:手动转换为UTF-8字节数组传递

将字符串直接转换为UTF-8字节数组,再作为RequestBody参数添加:

var
  RESTClient1: TRESTClient;
  RESTRequest1: TRESTRequest;
  lBody: string;
  lUTF8Bytes: TBytes;

lBody := '{"value": "testäöü"}';
// 将Unicode字符串转换为UTF-8字节数组
lUTF8Bytes := TEncoding.UTF8.GetBytes(lBody);

RESTClient1 := TRESTClient.Create(myUrl);
try
  RESTRequest1 := TRESTRequest.Create(RESTClient1);
  try
    RESTRequest1.Method := TRESTRequestMethod.rmPUT;
    RESTRequest1.AddAuthParameter('Authorization', 'Bearer ' + mySessionId, pkHTTPHEADER, [poDoNotEncode]);
    RESTRequest1.AddParameter('Content-Type', 'application/json; charset=utf-8', pkHTTPHEADER, [poDoNotEncode]);
    
    RESTRequest1.AddParameter('Body', lUTF8Bytes, pkREQUESTBODY, [poDoNotEncode]);
    RESTRequest1.Execute;

    if RESTRequest1.Response.StatusCode <> 200 then
    begin
      // 处理请求失败逻辑
    end;
  finally
    RESTRequest1.Free;
  end;
finally
  RESTClient1.Free;
end;

额外注意

原代码中使用&quot;转义双引号是多余的,Delphi字符串内部的双引号可以直接书写(用单引号包裹字符串即可),修复后的代码更易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 21:33:17