Erlang发送HTTP请求(Get,Post)

来源:互联网 发布:网络攻击的种类 编辑:程序博客网 时间:2024/05/20 01:11

在开发项目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} ->        Causeend;

发送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} ->        Causeend;

发送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} ->        Causeend;

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

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

1 0