简体   繁体   中英

Pass query params to Erlang HTTP Request

I'm trying to send parameters with an URL, like http://localhost:3000/register?name=Chris&job=typist . I can send that all at once as a string with httpc:request , but I can't find a function to put the query parameters in the URL(given a dictionary).

Is there another HTTP library I should be using that has this capability?

I'd like to give it a root URL with a hash/dictonary/map (in json {"a" : "b", "c" : "d"}) that then appends it correctly to the end of the url. For example, given "www.facebook.com" and [{"a", "b"}, {"c", "d"}] would give "www.facebook.com?a=b&c=d" .

Here is a similar question for Ruby: Ruby: How to turn a hash into HTTP parameters?

I'm not sure exactly what you mean by "hash", but if you'd like to construct a query string from tuples, that is a fairly straitforward task.

I'm not familiar with a method in httpc to provide the functionality you desire. You can write a wrapper around request/4 very easily, similar to this.

(This program is hastily constructed to give you the idea, forgive any errors).

request(Method, Domain, {Path, Query, Fragment}, HTTPOptions, Options) -> 
    QueryString = lists:flatten([Path,
                   case Query of "" -> ""; _ -> [$? | Query] end,
                   case Fragment of "" -> ""; _ -> [$# | Fragment] end]);
    Request = concat(Domain, QueryString);
    httpc:request(Method, {Request, []}, HTTPOptions, Options).

You can invoke it like

request(get, "http://www.example.com", {"/path", "", "bar?baz}, HTTPOptions, Options)

try this function

test(URL,QP)->URL++"?"++loop(QP,[]).

loop([{A,B}],QP)->QP++A++"="++B;
loop([{A,B}|T],QP)->loop(T,QP++A++"="++B++"&").

call test("www.facebook.com",[{"a", "b"}, {"c", "d"}]). it returns "www.facebook.com?a=b&c=d" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM