I'm sending a number of parameters to an API using the TIdHTTP.Get()
method.
I pull values for the actual API parameters from string
variables or component Text
properties (like a ComboBox
, for example). Everything is fine until any of those values contains a space.
For example, one of the parameters is a full name field (example: 'John Smith'
)
Since it contains a space between the first and last name, once I send it to the API using te TIdHTTP.Get()
method, it throws a 400 Bad Request
error and fails.
If I eliminate the space from the value for that/any particular parameter, it goes through fine.
Code I'm using to test:
httpObject := TIdHTTP.Create;
httpObject.HTTPOptions := [hoForceEncodeParams];
httpobject.MaxAuthRetries := 3;
httpObject.ProtocolVersion := pv1_1;
httpObject.Request.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
httpObject.Request.UserAgent := 'Mozilla/3.0 (compatible;Indy Library)';
httpObject.Request.ContentType := 'application/x-www-form-urlencoded; charset=utf-8';
URL := 'url string containing the parameters'; //string variable
httpObject.Get(URL);
API documentation says:
How can I address this?
Using Delphi Community Edition (which is 10.3) and its accompanying Indy components.
You have stated that you are submitting the data as Content-Type: application/x-www-form-urlencoded
That format does not allow spaces. You need to properly encode what you are submitting.
Two ways you can do this:
With Indy:
Encoded := TIdURI.URLEncode(str);
With TNetEncoding
Encoded := TNetEncoding.URL.Encode(str);