I have not been working with Monotouch (or the iphone for that matter) for too long, so I guess my problem is experience related.
I created an application that needs to communicate with a web service via json. I used the ported Json.NET library found here : https://github.com/chrisntr/Newtonsoft.Json
First I created a windows application using the Json.NET library, just to quickly try it out. It worked perfectly. Then I wrote the same exact code in MonoDevelop, and the server returns an error message that it cannot recognize the query at all. Note that I have checked if the serializer does its job properly - the json string is formatted correctly. Moreover, both applications behave in the same manner until getting the response from the server.
JsonSerializer serializer = new JsonSerializer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(the uri of the service);
request.Method = "post";
request.ContentType = "application/x-www-form-urlencoded";
Query login = new Query(); // the object that will be serialized
login.module = "auth";
login.data.Add("username", username goes here);
login.data.Add("password", password goes here);
using (Stream s = request.GetRequestStream())
{
using (StreamWriter w = new StreamWriter(s))
{
StringWriter sWriter = new StringWriter(new StringBuilder());
serializer.Serialize(sWriter, login);
w.Write("&query="+sWriter.ToString());
}
}
using (HttpWebResponse resp = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(resp.GetResponseStream());
JsonReader r = new JsonTextReader(reader);
Response login_response = (Response)serializer.Deserialize(reader, typeof(Response));
}
When I first wrote the windows application, the server could not recognize my queries because the Content header was set to "application/json" and because it requires the query to be delivered as a key-value pair (with "开发者_开发知识库query" as the key). That is the reason for the w.Write("query = "+sWriter.ToString()); . In the php script that was provided as an example of calling the service, this line was setup like this: curl_setopt($ch, CURLOPT_POSTFIELDS, array('query'=>jsonEncode($data)));
However since I fixed the content type headers and added the "query=" in front of the string, the code works perfectly in Visual Studio and Mono Develop. It even ran on my android phone after I wrote it in Java. However, in MonoTouch, the server always fails to recognize the request stream as a query. What could be the cause of this? is there anything special that happens to the request stream in MonoTouch as opposed to everywhere else? Again, I have checked the string that gets into the stream, it is correct and the same for all the test applications.
Thank you in advance.
Reinstalled MonoDevelop and issue disappeared.
精彩评论