Search code examples
restdelphidelphi-xe6

Delphi RESTClient POST request


Well, I'm developing a REST Client application that needs to send a POST request using application/x-www-form-urlencoded as Content type. I'm using Delphi's default REST.Client components. I need to send data in XML format, like the following example:

    data=<serviceLocal>
    <description>Francisco Hansen</description>
    <active>true</active>
    <corporateName>Francisco Hansen</corporateName>
    <country>Brasil</country>
    <state>PR</state>
    <city>Pato Branco</city>
    <cityNeighborhood>Centro</cityNeighborhood>
    <streetType>Rua</streetType>
    <street>Tocantins</street>
    <streetNumber>2334</streetNumber>
    <streetComplement>Ap101</streetComplement>
    <zipCode>85501-272</zipCode>
    <cellphoneStd>46</cellphoneStd>
    <cellphoneNumber>99999999</cellphoneNumber>
    <phoneStd>46</phoneStd>
    <phoneNumber>99999999</phoneNumber>
    </serviceLocal>

How can I add all these as POST parameters to a TRestRequest and then send this request using a TRestClient?


Solution

  • Using a Rest.Client.TRESTRequest component, I've been able to set the POST parameters for the request. I've named the TRESTRequest as rqst1

    .

    rqst1.Method := rmPost;
    
    rqst1.Params.AddItem; //Adds a new Parameter Item
    rqst1.Params.Items[0].name := 'data'; //sets the name of the parameter. In this case, since i need to use 'data=' on the request, the parameter name is data.
    rqst1.Params.Items[0].Value := params; //Adds the value of the parameter, in this case, the XML data.
    rqst1.Params.Items[0].ContentType := ctAPPLICATION_X_WWW_FORM_URLENCODED; //sets the content type.
    rqst1.Params.Items[0].Kind := pkGETorPOST; //sets the kind of request that will be executed.