Send special character in Request body via Httprequest in Delphi XE2?

Asked

Viewed 469 times

0

I am consuming an API (POST), via Delphi for sending NF-e XML. I am using Httprequest.

In the body of the request (body) I must pass the xml as follows: xml=

But the issuer’s social reason (xName) contains the special character "&". By sending the information to the API it returns an error:

Note XML with broken or invalid syntax: Premature end of data in tag xNome line 1

From what I understand, the API is understanding that this & refers to a new parameter, breaking the XML string.

How do I send information with this special character "&" so that the API does not understand as parameter but as text/string of Xml?

My code is like this:

Request.Uri := BASE_URL + '?token='+ FToken;
Request.Method := 'POST';
Request.Headers.SetValue('Accept', 'application/xml');
Request.Headers.SetValue('Content-Type', 'application/x-www-form-urlencoded');
Request.Headers.SetValue('Authorization', 'Basic '+EncodeString(Format('%s:%s', [FUsuario, FSenha])));
Request.SetContent(TEncoding.UTF8.GetBytes(Concat('xml=', FXML.Text)));
  • Try to change the & for & and see if it resolves.

1 answer

0

You only need to use the escape characters.

Escape character is a way for you to say that character & is a character really and not just a parameter.

If you put a character like < inside an element XML element, it will generate an error because the parser interprets it as the start of a new element.

To avoid this, you must replace the character < by an entity reference, thus:

That:

<mensagem>se saldo < 1000 então não tenho dinheiro</mensagem>

Turn that around:

<mensagem>se saldo &lt; 1000 então não tenho dinheiro</mensagem>

There are 5 predefined entity references in XML:

"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

Then when informing the issuer’s corporate name, simply change the & for &amp;

You can see a little more about that in this link, in this here and in this other also.

  • Thanks for the help but didn’t solve. I identified the problem through Postman. By Postman the Xml is passed in the body by the type x-www-form-urlencoded (key=value). But I can’t find the option in Httprequest to pass this way. Setcontent writes directly to body/raw (invalid here)

  • So... you know Acbr? It is an open source component that is well used to handle Dfes, with it you do not need to keep mounting the entire XML of the note in hand, is the tip if you do not know!

  • 1

    Yes I know and use Matheus. The API I refer to is not for issuance. It is a third-party API for storing/storing NF-e XML.

  • felipearon, can do Httpreq.Request.Contenttype := 'application/x-www-form-urlencoded'; no?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.