Delphi 7 IdHTTP POST 中文乱码得解决

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

解决方法:

1.先把AnsiString转WideString

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

代码示例:

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;
  

你可能感兴趣的:(开发语言,Delphi)