How do you URL encode parameters in Erlang?

前端 未结 8 1122
清歌不尽
清歌不尽 2020-12-31 01:17

I\'m using httpc:request to post some data to a remote service. I have the post working but the data in the body() of the post comes through as is, without any URL-encoding

8条回答
  •  萌比男神i
    2020-12-31 01:42

    Here's a simple function that does the job. It's designed to work directly with 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)).
    

    Example usage:

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

提交回复
热议问题