Problems sending JSON requests using POST
It appears as though the setRequestHeader gets ignored for a HTTPClient which is being used to POST.
I have a REST service which consumes and produces application/json. however it doesn't like the requests from Titanium because requests are always sent with content-type:x-www-form-urlencoded regardless of what you specify using setRequestHeader().
Is this a bug? Is there a possible workaround?
var xhr = Titanium.Network.createHTTPClient();
xhr.onreadystatechange = function() {
try {
if (this.readyState == 4) {
var results = JSON.parse(this.responseText);
}
} catch(e) {
Ti.API.debug(e.error);
}
};
xhr.open("POST","http://myrestserviceurl");
xhr.setTimeout(10);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send('{"value1":"x","value2":"y"}');
7 Answers
-
I recently tested and fixed this bug (or so I thought..), which version of the mobile sdk is your project using? (you can check in the "Edit" tab of developer)
-
Thanks Marshall,
I'm using Titanium 1.1.2 on Windows. With Android 1.6 sdk.
-
Hmm.. Try sending the JSON inline instead of as a raw string (this is how our current test works)
-
I'm sending my request as follows and it is now sending the POST as application/json (perhaps it was before and i was getting confused).
However the message gets sent all garbled. Are you able to show me a working example of how to send json data?var xhr = Titanium.Network.createHTTPClient(); xhr.onreadystatechange = function() { try { if (this.readyState == 4) { var results = JSON.parse(this.responseText); } } catch(e) { Ti.API.debug(e.error); } }; xhr.open("POST","http://myrestserviceurl"); xhr.setTimeout(10); xhr.setRequestHeader("Content-Type","application/json; charset=utf-8"); xhr.send({"value1":"x", "value2":"y"});
-
We are having the same problem as identified above, but when we did as one of the answers above suggested it still did not work, our server still sees the request as a form and not a json post. It seems the content type is not getting set during a post. Any ideas?
-
We had a bug like this in our app. The problem was we were sending an object instead of a string. The error message about incorrect content-type seems to be wrong. After changing our code to send a string instead of an obejct it worked fine.
-
you should give URL with local host or the server IP address followed by port number….I think it works