如何在Ballerina中的POST请求中发送表单数据?

时间:2018-07-05 19:51:16

标签: ballerina

我想通过POST请求发送表单数据。我尝试设置标头和设置有效载荷。

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

结果为

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

使用setStringPayload方法时,

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

发生如下错误。

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

我正在使用Ubuntu 16.04和Ballerina 0.975.0

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

出现以下错误的原因是未正确覆盖内容类型。

  

{message:“实体主体自收到以来不兼容json   内容类型为:文本/纯文本”,原因:空}

setPayload方法通过方法参数推断有效载荷的类型并设置各自的默认参数。在这种情况下,有效载荷是字符串类型,因此content-type设置为text / plain。 addHeader方法不会替换现有的标头值,因为它只是为特定的现有标头名称添加了另一个条目。

由于第一个enty内容类型被赋予优先级,所以它仍然是text / plain。解决方案是使用setHeader替换现有的标头值。

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

关于第二个查询,setStringPaylaod重命名为setTextPaylaod。因此,使用以下代码可以发送表单数据。覆盖内容类型很重要,因为通过setTextPaylaod设置有效负载的默认内容类型是text / plain。

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

getFormParams方法可用于将参数作为地图检索。

相关问题