Skip to content

Instantly share code, notes, and snippets.

@flitbit
Created April 29, 2014 01:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flitbit/11388377 to your computer and use it in GitHub Desktop.
Save flitbit/11388377 to your computer and use it in GitHub Desktop.
how-to-support-chinese-in-http-request-body-erlang
%% -*- 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}}.
@flitbit
Copy link
Author

flitbit commented Apr 29, 2014

If you casually find this code, note that concatenating strings to build JSON as in line #17 is not a technique I would use or recommend.

When I answered this question on stack-overflow I wanted to address the question and its solution, not an entirely different approach. Admittedly "don't do that" would have been a valid alternate answer, but I needed to work through the underlying issue anyway.

What I would recommend is using jiffy or mochijson2 to encode data from Erlang into JSON.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment