Senuri De Silva
Senuri De Silva

Reputation: 112

How to send form data in a POST request in Ballerina?

I want to send form data with the POST request. I have tried setting up the headers and setting payloads.

req.setPayload("text=you are amazing");
req.addHeader("content-type","application/x-www-form-urlencoded");

It results as,

{message:"Entity body is not json compatible since the received content-type is : text/plain", cause:null}

When the setStringPayload method is used,

req.setStringPayload("text=you are amazing");
req.addHeader("content-type","application/x-www-form-urlencoded");

an error occurs as follows.

error: senuri/sms-sender:1.0.0/sms_sender.bal:72:5: undefined function 'setStringPayload' in struct 'ballerina/http:Request'

I am on Ubuntu 16.04 and Ballerina 0.975.0

Any suggestions ?

Upvotes: 1

Views: 770

Answers (1)

Chamil E
Chamil E

Reputation: 478

Reason for getting below error is the content type is not properly overridden.

{message:"Entity body is not json compatible since the received content-type is : text/plain", cause:null}

setPayload method infers the type of payload by the method parameter and set respective default parameter. In this instance, payload is string type, so content-type is set as text/plain. addHeader method doesn't replace existing header values as it just adds another entry for particular existing header name.

Since priority is given to the first enty content-type is still text/plain. Solution is to use setHeader which replaces the existing header value.

req.setPayload("text=you are amazing");
req.setHeader("Content-type","application/x-www-form-urlencoded");

Regarding the second query, setStringPaylaod is renamed to setTextPaylaod. So using following code, form data can be sent. Overriding content-type is important as default content type for setting payload via setTextPaylaod is text/plain.

req.setTextPayload("text=you are amazing");
req.setHeader("Content-type","application/x-www-form-urlencoded");

getFormParams method can be used to retrieve param as a map.

Upvotes: 3

Related Questions