1

我想用 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

有什么建议么 ?

4

1 回答 1

3

低于错误的原因是内容类型未被正确覆盖。

{消息:“实体主体与 json 不兼容,因为接收到的内容类型是:text/plain”,cause:null}

setPayload方法通过方法参数推断负载的类型并设置相应的默认参数。在本例中,payload 为字符串类型,因此 content-type 设置为 text/plain。 addHeader方法不会替换现有的标头值,因为它只是为特定的现有标头名称添加另一个条目。

由于优先考虑第一个实体内容类型仍然是文本/纯文本。解决方案是使用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方法可用于将参数作为地图检索。

于 2018-07-06T02:10:35.860 回答