如何使用Tidhttp发送带有名为xml的参数的Get请求?

3
我一直在成功使用 Delphi 2010 发送 http get 请求,但对于某个需要名为 'xml' 的参数的服务,请求失败并显示 'HTTP/1.1 400 Bad Request' 错误。
我发现,如果不带上 'xml' 参数调用同一个服务,则可以正常工作。
我尝试了以下方法,但都没有成功:
HttpGet('http://localhost/Service/Messaging.svc/SendReports/PDF?xml=<?xml version="1.0"?><email><message><to>email@internal.com</to><from>from@internal.com</from></message></email>&id=42&profile=A1');

...

function TReportingFrame.HttpGet(const url: string): string;
var
  responseStream : TMemoryStream;
  html: string;
  HTTP: TIdHTTP;
begin
  try
      try
        responseStream := TMemoryStream.Create;
        HTTP := TIdHTTP.Create(nil);
        HTTP.OnWork:= HttpWork;
        HTTP.Request.ContentType := 'text/xml; charset=utf-8';
        HTTP.Request.ContentEncoding := 'utf-8';
        HTTP.HTTPOptions := [hoForceEncodeParams];
        HTTP.Request.CharSet := 'utf-8';
        HTTP.Get(url, responseStream);
        SetString(html, PAnsiChar(responseStream.Memory), responseStream.Size);
        result := html;
      except
        on E: Exception do
            Global.LogError(E, 'ProcessHttpRequest');
      end;
    finally
      try
        HTTP.Disconnect;
      except
      end;
    end;
end;

将具有参数名称“xml”的相同url调用重命名为任何其他名称,例如“xml2”或“name”,并具有与上述相同的值也可以正常工作。我还尝试了多种字符集组合,但我认为indy组件在内部进行了更改。

编辑

该服务期望:

[WebGet(UriTemplate = "SendReports/{format=pdf}?report={reportFile}&params={jsonParams}&xml={xmlFile}&profile={profile}&id={id}")]

有人有这方面的经验吗?

谢谢


OT:您可以调用返回字符串的TIdHTTP.Get重载,并将其直接分配给Result。这将允许您删除当前泄漏的流部分。 - TLama
有关编程的内容的翻译:关于文本/ XML 字符集/错误请求问题,有何建议? - reckface
抱歉,是的。我可以从Web浏览器调用上述URL。我可以使用完全相同的URL从.Net应用程序中调用它,但无法从Delphi中调用。仅在Delphi中存在名为“xml”的参数会导致问题。 - reckface
URLEncode 导致 HTTP 500 服务器错误。 - reckface
你还没有展示那个参数的具体规范……好吧,由你决定。既然你已经有了可工作的实现,请确保 Delphi 应用程序的行为与这些可工作的程序相匹配。http://stackoverflow.com/questions/17546558/ - Arioch 'The
显示剩余5条评论
1个回答

7

当通过URL传递参数数据时,您需要对其进行编码。 TIdHTTP 不会为您对URL进行编码,例如:

http.Get(TIdURI.URLEncode('http://localhost/Service/Messaging.svc/SendReports/PDF?xml=<?xml version="1.0"?><email><message><to>email@internal.com</to><from>from@internal.com</from></message></email>&id=42&profile=A1'));

或者:

http.Get('http://localhost/Service/Messaging.svc/SendReports/PDF?xml=' + TIdURI.ParamsEncode('<?xml version="1.0"?><email><message><to>email@internal.com</to><from>from@internal.com</from></message></email>') + '&id=42&profile=A1');

谢谢!解决了。原来是http 500错误确实来自服务器,原因是客户端检测到一个潜在危险的Request.QueryString值。我已经相应地修改了web.config文件。 - reckface

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接