Delphi 7 IdHTTP POST 中文乱码得解决

WEB后台使用UTF-8进行编码,由于D7默认是ansiString,直接提交到后台会使中文乱码。

解决方法:

1.先把AnsiString转WideString

2.通过System单元中的ansitoUTF8()函数进行转换之后再提交就可以了。

代码示例:

Delphi 复制代码
procedure postDemo();
var
  AURL: String;
  APostList: TStringList; // 提交参数List
  APostStream : TStringStream; // 流提交
  APostWideString:WideString;
  AResponseStream: TStringStream; // 接收流
  AResponse: String;
begin
  AURL:=''; // 接口地址
  AResponseStream := TStringStream.Create('');
  APostList:= TStringList.Create; 
  APostList.add('user=测试');
  APostList.add('id=123456');
  APostList.add('code=HA123');
  APostWideString := APostList.text;
    
  APostStream :=TStringStream.Create(ansitoUTF8(APostWideString));

  try 
    // WideString 调用ansitoUTF8进行UTF-8编码才行
    APostList.text := ansitoUTF8(APostWideString);

    IdHTTP.Request.ContentType := 'application/x-www-form-urlencoded; Charset=UTF-8';

    // List 提交
    IdHTTP.Post(AURL, APostList, AResponseStream);

    // 字符串提交
    IdHTTP.Post(AURL, ansitoUTF8(APostWideString), AResponseStream);

    // 流提交
    IdHTTP.Post(AURL, APostStream, AResponseStream);

    // AResponse 接收到的返回用UTF-8解码
    AResponse := UTF8toansi( AResponseStream.DataString );
    
  finally
    APostList.Clear;
    APostList.Free; 
    APostStream.Free;
    AResponseStream.Free;
  end; 

end;
  
相关推荐
破茧蝴蝶5 小时前
Python分布式爬虫完整教程
开发语言·python
狗凯之家源码网5 小时前
全新 PHP 轻量客服聊天室源码深度评测
开发语言·php·聊天室系统
远离UE45 小时前
UE5 Substrate Thin Film 源码拆析
开发语言·javascript·ue5
keyipatience6 小时前
JavaScript学习(1)书写位置,变量、数据类型、运算符
开发语言·前端·javascript·css·学习
栈帧之外6 小时前
【C++】STL之set
开发语言·c++
catchadmin7 小时前
免费可商用 PHP 管理后台 CatchAdmin V5.4.1 发布,新增 MCP 支持
开发语言·php
jimy18 小时前
c++的 Type Traits (二、更详细版本)
开发语言·c++
狗凯之家源码网9 小时前
纯 PHP+MySQL 应用市场系统源码实测!
开发语言·mysql·php
dishugj9 小时前
系统架构风险点、敏感点和权衡点的概念和区分
java·开发语言
geovindu9 小时前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模