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;
  
相关推荐
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月4 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237174 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian4 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript
雪人不是菜鸡4 天前
简单工厂模式
开发语言·算法·c#