by
0
4
1,327
0
Top 1% !
Popular
Famous
Specified
Popularity: 17511st place
Created
Modified Apr 29, 2014

Published on:

No tags for this snippet yet.
LanguageErlang
LicenseMIT_X11
SourceGithub

how-to-support-chinese-in-http-request-body-erlang

how-to-support-chinese-in-http-request-body-erlang: 
example.erl
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/51463/how-to-support-chinese-in-http-request-b?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
%% -*- coding: utf-8 -*- -module(example). -export([ url/0, content/0, http_post_content/2, verify_response/2 ]). url() -> "http://localhost:3000/". content() -> "我是中文". http_post_content(Url, Content) -> ContentType = "application/json", %% Concat the list of (character) lists Body = lists:concat(["{\"content\":\"", Content, "\"}"]), %% Explicitly encode to UTF8 before sending UnicodeBin = unicode:characters_to_binary(Body), httpc:request(post, { Url, [], % HTTP headers ContentType, % content-type UnicodeBin % the body as binary (UTF8) }, [], % HTTP Options [{body_format,binary}] % indicate the body is already binary ). verify_response({ok, {{_, 200, _}, _, Response}}, SentContent) -> %% use jiffy to decode the JSON response {Props} = jiffy:decode(Response), %% pull out the "content" property's value ContentBin = proplists:get_value(<<"content">>, Props), %% convert the binary value to unicode characters, %% it should equal what we sent. case unicode:characters_to_list(ContentBin) of SentContent -> ok; Other -> {error, [ {expected, SentContent}, {received, Other} ]} end; verify_response(Unexpected, _) -> {error, {http_request_failed, Unexpected}}.
If you want to be updated about similar snippets, Sign in and follow our Channels