Monday, August 6, 2007

The final request the post your Atom message.

The final request to post the message in the atom format:

request(AuthToken, BlogId, Data) ->
Body = iolist_to_binary(Data),
io:format("Sending: ~nContent-length: ~p~nBody:~n~s~n", [ size(Body), Body ]),
Authorization = "GoogleLogin auth=" ++ AuthToken,
Url = "http://www.blogger.com/feeds/" ++ BlogId ++ "/posts/default",
case http:request(post, % Method ;)
{
Url, % URL
[ { "Authorization", Authorization } ], % Headers
"application/atom+xml; charset=utf-8", % Content-type
Body % Body
},
[ {timeout, 3000}, {sync, false} ], % HTTPOptions
[ {body_format, binary} ]) of % Options

{ok, Result} ->
case Result of
{{_, 201, _}, Headers, _Response} ->
PostId = get_postid(Headers),
{ok, PostId};

{_,_,Response} ->
Response
end;

{error, Reason} ->
io:format("Error: ~p~n", [Reason])
end.

The thing that's cool overthere is the 'get_postid/1' to retrieve the postId generated by the blogger api... This fun will be called only when the HTTP 'status' code will be "201", which means "created".

I parse response headers and search for 'location' string, and once found I extract the last part of the url:

get_postid([]) ->
"none";
get_postid(Headers) ->
case lists:keysearch("location", 1, Headers) of
{value, {_, Value}} ->
lists:last( string:tokens(Value, "/") );

_ ->
"none"
end.

I've look at the Zend Framework, and found that it parse the entire response body to extract the same value... I think that my method is simpler and works better. That's also why erlang is for smarter people than php (gratuitous troll :p)

No comments:

Sticky