How can I use Tidhttp to make a Get request with a

2019-02-25 03:35发布

问题:

I've been successfully using Delphi 2010 to make an http get requests, but for one service that expects a parameter called 'xml' the request fails with a 'HTTP/1.1 400 Bad Request' error.

I notice that calling the same service and omitting the 'xml' parameter works.

I have tried the following with no success:

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;

Calling the same url with the parameter name 'xml' renamed to anything else, like 'xml2' or 'name' with the same value as above also works. I have also tried multiple combinations of the charset, but I think the indy component is changing it internally.

EDIT

The service expects:

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

Has anyone had any experience with this?

Thanks

回答1:

You need to encode the parameter data when passing it via a URL, TIdHTTP will not encode the URL for you, eg:

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'));

Or:

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');