delphi - Delphi 2010 中的 Indy IdHttp Post 问题

标签 delphi http unicode delphi-2010 indy

我对 Indy IdHttp Post 方法有疑问。 使用 Delphi 2007 编译的函数 CallRpc() 工作正常,但使用 Delphi 2010 编译的相同代码会引发异常。

将 Delphi 2007 Indy TIdHttp 更改为 Delphi 2010 Indy TIdHttp 时需要考虑什么?

function CallRpc(const sURL, sXML: string): string;
var
  SendStream : TStream;
  IdHttp     : TIdHttp;
begin
  SendStream := TMemoryStream.Create;
  IdHttp := TIdHttp.Create(nil);
  try
      IdHttp.Request.Accept        := '*/*';
      IdHttp.Request.ContentType   := 'text/sXML';
      IdHttp.Request.Connection    := 'Keep-Alive';
      IdHttp.Request.ContentLength := Length(sXML);

      StringToStream(sXML, SendStream);  
      SendStream.Position := 0;

      Result := IdHttp.Post(sURL, SendStream);
  finally
    IdHttp.Free;
    SendStream.Free;
  end;
end;

2009 年 1 月 25 日新增:

异常是这样的:EIdConnClosedGracefully

响应是这样的:

<?xml version='1.0' encoding='us-ascii'?>
<!DOCTYPE Error [ <!ELEMENT Error (ErrorMessage,DebuggingInfo*)> <!ATTLIST Error Date CDATA #REQUIRED Time CDATA #REQUIRED> <!ELEMENT ErrorMessage (#PCDATA )>  <!ELEMENT DebuggingInfo (#PCDATA )> ] >
<Error Date='01/25/2010' Time='08:57:12'>
<ErrorMessage>
    XML SERVER ERROR: There was a SYSTEM ERROR error in the Incoming XML Response: $ZE=&lt;UNDEFINED&gt;lexan+196^%eXMLLexAnalyzer
</ErrorMessage>

解决方案 26.1.2009:

function CallRpc(const sURL, sXML: string): string; 
var 
  SendStream : TStream; 
  IdHttp     : TIdHttp; 
  sAnsiXML: Ansistring;   // <-- new
begin 
  sAnsiXML := sXML;  // <-- new: Implicit string cast

  SendStream := TMemoryStream.Create; 
  IdHttp := TIdHttp.Create(nil); 
  try 
     IdHttp.Request.Accept        := '*/*'; 
     IdHttp.Request.ContentType   := 'text/sXML'; 
     IdHttp.Request.Connection    := 'Keep-Alive'; 
     IdHttp.Request.ContentLength := Length(sAnsiXML); // <-- new

     SendStream.Write(sAnsiXML[1], Length(sAnsiXML));  // <-- new
     SendStream.Position := 0; 

     Result := IdHttp.Post(sURL, SendStream); 
  finally 
   IdHttp.Free; 
   SendStream.Free; 
  end; 

结束;

最佳答案

contentLength 以八位字节为单位,您的字符串长度以字符为单位。由于 sizeof( Char ) = 2 在 Delphi 2009+ 中,这是不匹配的!

也许将 XML 与 UTF8 字符串相互转换会更好。一些应用程序不支持 USC2 Unicode 格式。

您应该提供结果流的大小作为 ContentLength。

更好的是:不要提供 ContentLength 并让 Indy 为您完成..

关于delphi - Delphi 2010 中的 Indy IdHttp Post 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2122663/

相关文章:

delphi - Firemonkey组件中旋转时如何避免重复图像?

python - UnicodeEncodeError - 在 Spyder 中有效,但从终端执行时无效

delphi - 从原始像素数据数组加载 TPicture

mysql - SQL 和 Delphi : recursive mechanism for creating a tree from a table

html - 设置图像的真实 HTML 高度和宽度会减少加载时间吗?

objective-c - iPad/objective-C 同步 HTTP 请求示例?

java - Unicode 适用于 Windows 但不适用于 Red Hat Linux : Java

c++ - 以 L 开头的宽字符串文字(如 L“Hello World”)是否保证以 Unicode 编码?

Delphi Rad Studio - 每次编译/构建时我可以停止重新编译组件吗

javascript - hittng http post 请求后无法执行成功 block