您的位置:首页 > 理论基础 > 计算机网络

erlang HTTP 客户端 使用实例

2015-09-28 10:33 411 查看
HTTPC的请求范式

HTTPC(Method(),Request(),Httoptions().Options()) 其中

Method=head|get|put|psot|trace|options|delete (一般主要用 get ,post ,put ,delete)

Request= {url(),headers()}|{url(),headers(),content_type(),body()}

前者用于 get ,后者一般用于post ,put ,而delet 方法取决于你URL的设计

Url () 就是 请求的地址 不过注意,必须加上http 的前缀啊 就像http://myapp.com:8080 ,使用myapp.com:8080 会报错

headers={filed(),Value()} 是 HTTP请求头的属性键值表,例子:[{"content-length","216"}] 注意 键和值都是字符串啊

content-type= strings() 就是传输内容的类型 例子 “application/json" 说明传递的是字符串

body() =strings() 不要解释了,就是Http的内容了

JOSN 的erlang 库

JOSN的库有几个,我选择了这个

https://github.com/tonyg/erlang-rfc4627

Joe Armstrong对JSON数据数据映射的描述:http://erlang.org/pipermail/erlang-questions/2005-November/017805.html

JSON Obj = type obj() = {obj, [{key(), val()}]}
JSON Array = type array() = [val()]
JSON Number = type num() = int() | float()
JSON String = type str() = bin()
JSON true false null = true, false null (atoms)
With Type val() = obj() | array() | num() | str() | true | false | null
and key() being a str(). (Or a binary or atom, during JSON encoding.)

用其中的一个 rfc4627.erl 的文件就可以对json 编码解码了

1.如果POST的对象是个 键-值对象

rfc4627:encode({obj,[{user,"mike"},{password,"1234"}]} )

2 如果POST的是个键-值对象数组

rfc4627:encode([{obj,[{user,"mike"},{password,"1234"}]},

         {obj,[{user,"mike"},{password,"1234"}]}]

)

实例

1.获取 www.myapp.com 端口为8080 的内容

inets:start()

inets:start().
{ok,Result}=httpc:request(get,{"http://myapp.com:8080?user-mike",[]},[],[]).


2 使用以上例子 我加上一个 user参数

inets:start().
{ok,Result}=httpc:request(get,{"http://myapp.com:8080?user=mike",[]},[],[])


3 向www.myapp.com 提交一个JSON 。JOSN是个键-值对象 user="mike",password= "1234"

inets:start().
Msg=rf4627:encode({obj,[{user,"mike",password,"1234"}]})
{ok,Result}=httpc:request(post,{"http://myapp.com:8080",[],applcation/json,Msg},[],[]).


注意:在使用JOSN 库之前,先要使用code:add_path("你的JOSN库的beam 文件路径") 把这个库载入进来
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: