Erlang中的URL编码

dav*_*ley 20 url erlang encoding http

我正在使用erlang http:request将一些数据发布到远程服务.我有帖子工作,但帖子的body()中的数据按原样通过,没有任何url编码导致帖子在远程服务解析时失败.

在Erlang中是否有一个函数类似于Ruby中的CGI.escape用于此目的?

小智 23

我在HTTP模块中也遇到了这个功能.

事实证明,这个功能实际上在erlang发行版中可用,你只需要看起来很难.

> edoc_lib:escape_uri("luca+more@here.com").
"luca%2bmore%40here.com"
Run Code Online (Sandbox Code Playgroud)

它的行为类似于Ruby中的CGI.escape,还有URI.escape,其行为略有不同:

> CGI.escape("luca+more@here.com")
 => "luca%2Bmore%40here.com" 
> URI.escape("luca+more@here.com")
 => "luca+more@here.com" 
Run Code Online (Sandbox Code Playgroud)

edoc_lib

  • 似乎这个建议已经过时——点击链接,你会看到 `edoc_lib:escape_uri` 是 MIA。不确定哪个 erlang 版本引入了此更改。 (2认同)

小智 10

至少在R15中有http_uri:encode/1来完成这项工作.我也不建议使用edoc_lib:escape_uri将'='转换为%3d而不是%3D,这会给我带来一些麻烦.


Bwo*_*oce 9

你可以在这里找到YAWS url_encode和url_decode例程

它们相当简单,虽然注释表明编码对于所有标点符号都不是100%完整的.


小智 7

这是一个完成这项工作的简单功能.它旨在直接使用inets httpc.

%% @doc A function to URL encode form data.
%% @spec url_encode(formdata()).

-spec(url_encode(formdata()) -> string()).
url_encode(Data) ->
    url_encode(Data,"").

url_encode([],Acc) ->
    Acc;

url_encode([{Key,Value}|R],"") ->
    url_encode(R, edoc_lib:escape_uri(Key) ++ "=" ++ edoc_lib:escape_uri(Value));
url_encode([{Key,Value}|R],Acc) ->
    url_encode(R, Acc ++ "&" ++ edoc_lib:escape_uri(Key) ++ "=" ++ edoc_lib:escape_uri(Value)).
Run Code Online (Sandbox Code Playgroud)

用法示例:

httpc:request(post, {"http://localhost:3000/foo", [], 
                    "application/x-www-form-urlencoded",
                    url_encode([{"username", "bob"}, {"password", "123456"}])}
             ,[],[]).
Run Code Online (Sandbox Code Playgroud)


小智 6

如果有人需要在 erlang 中使用 utf-8 编码 uri:

https://gist.github.com/3796470

前任。

Eshell V5.9.1  (abort with ^G)

1> c(encode_uri_rfc3986).
{ok,encode_uri_rfc3986}

2> encode_uri_rfc3986:encode("???").
"%e3%83%86%e3%82%b9%e3%83%88"

3> edoc_lib:escape_uri("???").
"%c3%86%c2%b9%c3%88" # output wrong: ƹÈ
Run Code Online (Sandbox Code Playgroud)