Erlang发送HTTP请求(Get,Post)

在开发项目Erlang程序项目中 , 用到了HTTP请求 , 主要是Get和Post , 其他的类似Put和Post请求模式一样 ; 现将代码总结如下 :

发送HTTP-Get请求

inets:start(),
ReqUrl = string:join(["http://www.example.com/user?access=",binary_to_list(Access)],""),
RstGet = httpc:request(ReqUrl ),
inets:stop(),

case  RstGet of
    {ok, {_,_,RstBody}} ->
        RstBody;  
    {error, Cause} ->
        Cause
end;

发送HTTP-Post请求

inets:start(),
ReqUrl = string:join(["http://www.example.com/access=",binary_to_list(Access)],""),
ParaStr = io_lib:format("phone=~s&vcode=~s",[Phone, Vcode]),
RegUsr = httpc:request(post,{ApiUrl, [],"application/x-www-form-urlencoded", list_to_binary(ParaStr)},[],[]),
inets:stop(),

case  RstGet of
    {ok, {_,_,RstBody}} ->
        RstBody;  
    {error, Cause} ->
        Cause
end;

发送HTTP-Post请求 , 上传文件

format_multipart_formdata(Boundary, Fields, Files) ->
% 遍历字符参数
    FieldParts = lists:map(fun({FieldName, FieldContent}) ->
        [lists:concat(["--", Boundary]),
            lists:concat(["Content-Disposition: form-data; name=\"",atom_to_list(FieldName),"\""]),
            "", FieldContent]
                           end, Fields),
FieldParts2 = lists:append(FieldParts),

% 遍历文件参数
FileParts = lists:map(fun({FieldName, FileName, FileContent}) ->
    [lists:concat(["--", Boundary]),
        lists:concat(["Content-Disposition: form-data; name=\"",atom_to_list(FieldName),"\"; filename=\"",FileName,"\""]),
        lists:concat(["Content-Type: ", "application/octet-stream"]), "", FileContent]
                      end, Files),
FileParts2 = lists:append(FileParts),
EndingParts = [lists:concat(["--", Boundary, "--"]), ""],
Parts = lists:append([FieldParts2, FileParts2, EndingParts]),
string:join(Parts, "\r\n").

--- Usage:

{ok,BinStream} = file:read_file("./images/avatar.png"),
Data = binary_to_list(BinStream), 
Boundary = "------WebKitFormBoundaryUscTgwn7KiuepIr1",
ReqBody = format_multipart_formdata(Boundary, [{uid,"123"}], [{avatar, "avatar", Data}]),
ContentType = lists:concat(["multipart/form-data; boundary=", Boundary]),
ReqHeader = [{"Content-Length", integer_to_list(length(ReqBody))}],

inets:start(),
ParaUrl = string:join(["http://www.example.com/avatar?access_token=",binary_to_list(token)],""),
RstGet = httpc:request(post,{ParaUrl, ReqHeader,ContentType, ReqBody},[],[])
inets:stop(),

case  RstGet of
    {ok, {_,_,RstBody}} ->
        RstBody;  
    {error, Cause} ->
        Cause
end;

参考资料: how to http:post file with httpc:request in erlang?

个人网站: Github , 欢迎点击给星

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值