使用inets http:request时请注意?

作者在调试程序过程中遇到使用inets_http_client发送Post请求时出现的问题,最初怀疑json编码错误,后发现是未按文档要求将deeplist转换为string或binary格式。
这两天在调试程序,今天刚刚去除了一个小bug:使用inets http client进行Post请求时,mochiweb 总是接收错误,开始怀疑json encode错误,否决;后来想到是不是http request错误呢?认真查看文档:
request(Method, Request, HTTPOptions, Options)
request() - {url(), headers(), content_type(), body()}
body() = string() | binary()
哦,原来是我没有认真的查看文档,这里的body是string或binary,不再是iolist了,而我使用mochijson2 encode后的数据是一个deep list,怪我把参数传递错了,没有认真看文档!

这里之所以疏忽,是因为我一直牢记Efficiency Guide 5.3 Deep and flat lists中的一条建议:
When sending data to a port. Ports understand deep lists so there is no reason to flatten the list before sending it to the port.

Post的数据毫无疑问是要通过gen_tcp发送的,最后也是要通过port发送的,所以我想都没有想就没有调用lists:flatten/1对数据进行处理。可是到了这里没有想到,风头一转,在httpc_request的body_length中,使用length(Body)获取Post数据长度。晕倒。

下面是R12B-5中相关的文档信息

http:request(Method, Request, HTTPOptions, Options)
request() - {url(), headers(), content_type(), body()}
body() = string() | binary()

gen_tcp:send(Socket, Packet)
Packet = [char()] | binary()
(实际中Packet可以为iodata())

erlang:port_command(Port, Data)
Data = iodata()
iodata() = iolist() | binary()
iolist() = [char() | binary() | iolist()]


本质上这几个函数都是调用port进行数据发送
为什么参数不统一都采用iodata呢?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值