I’m having trouble posting json data to a webservice using the ansynchronous http network.request call. Seems like the content-type of the body is always “application/x-www-form-urlencoded” regardless of how I try to set the header. I also tried setting the headers on a GET request with no luck.
The documentation on how to pass the parameters is a little ambiguous with regards to params/headers/body. Other than the headers the code below works.
I’m testing in the Corona simulator, build 268.
An http packet sniffer shows the same result as the test webservice.
A sinatra webservice to see what’s posted:
[ruby]
require ‘rubygems’
require ‘sinatra’
require ‘json’
post ‘/json’ do
puts “testing json post”
print "path_info: "; puts request.path_info
print "content_length: "; puts request.content_length
print "media_type: "; puts request.media_type
print "params.inspect: "; puts params.inspect
request.body.rewind # in case someone already read it
data = JSON.parse(request.body.read.to_s)
print "data.inspect: "; puts data.inspect
puts “done.”
“[html]Your response[/html]”
end
[/ruby]
The corona code that can post the body, but the headers don’t get set at all:
[lua]local json = require(“Json”)
local myText = display.newText("(Waiting…)", 0, 0, native.systemFont, 16)
myText.x = display.contentCenterX
myText.y = 120
local function networkListener( event )
if ( event.isError ) then
myText.text = “Network error.”
else
myText.text = “Done.”
print ( "Response: " … event.response )
end
end
local response, params, headers, body
local jsonData = {[“foo”] =“bar”}
body = Json.Encode(jsonData)
print (“jsonData=” … body)
print (“jsonData.length=” … string.len(body))
headers = {}
headers[“Content-Type”] = “application/json”
headers[“Content-Length”] = #body
headers[“From”] = “me@me.com”
headers.body = body
params = {}
params.headers = headers
params.body = body
local localUrl = “http://localhost:4567/json”
–network.request( localUrl, “POST”, networkListener, params ) – crashes
network.request( localUrl, “POST”, networkListener, headers ) --headers not set[/lua]
Output from sinatra for the above looks like this:
[text]
testing json post
path_info: /json
content_length: 13
media_type: application/x-www-form-urlencoded
params.inspect: {"{“foo”:“bar”}"=>nil}
data.inspect: {“foo”=>“bar”}
done.
[/text]
This curl script that works fine:
curl -H "Content-Type: application/json" -i -X POST "http://localhost:4567/json" -d '{"hi":"ho"}'
Output from sinatra for this curl script:
[text]
testing json post
path_info: /json
content_length: 11
media_type: application/json
params.inspect: {}
data.inspect: {“hi”=>“ho”}
done.
[/text] [import]uid: 6786 topic_id: 6318 reply_id: 306318[/import]
[import]uid: 52491 topic_id: 6318 reply_id: 70955[/import]