首页 > Web开发 > 详细

erlang HTTP 客户端 使用实例

时间:2015-09-28 11:17:20      阅读:256      评论:0      收藏:0      [点我收藏+]

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       = truefalse 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 文件路径") 把这个库载入进来

erlang HTTP 客户端 使用实例

原文:http://www.cnblogs.com/codewarelock/p/4843464.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!