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;
额外注意
原代码中使用"转义双引号是多余的,Delphi字符串内部的双引号可以直接书写(用单引号包裹字符串即可),修复后的代码更易读。
内容的提问来源于stack exchange,提问作者JonasK
相关产品推荐
相关产品推荐

