使用inets http:request時請注意?

這兩天在調試程序,今天剛剛去除了一個小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 篇原創文章 · 獲贊 0 · 訪問量 2864
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章