我已成功使用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’,其值与上面相同也可以.我也尝试了charset的多种组合,但我认为indy组件正在内部更改它.
编辑
该服务预计:
[WebGet(UriTemplate = "SendReports/{format=pdf}?report={reportFile}¶ms={jsonParams}&xml={xmlFile}&profile={profile}&id={id}")]
有没有人有这方面的经验?
谢谢
解决方法
您需要在通过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');