我使用HttpWebRequest从Web服务中获取,该服务返回了一个JSON字符串。看起来像这样的GET:
// Returns JSON stringstring GET(string url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); try { WebResponse response = request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8); return reader.ReadToEnd(); } } catch (WebException ex) { WebResponse errorResponse = ex.Response; using (Stream responseStream = errorResponse.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8")); String errorText = reader.ReadToEnd(); // log errorText } throw; }}然后,我使用JSON.Net动态解析字符串。另外,您可以使用以下Codeplex工具从示例JSON输出静态生成C#类:http
:
//jsonclassgenerator.preplex.com/
POST看起来像这样:
// POST a JSON stringvoid POST(string url, string jsonContent) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); Byte[] byteArray = encoding.GetBytes(jsonContent); request.ContentLength = byteArray.Length; request.ContentType = @"application/json"; using (Stream dataStream = request.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); } long length = 0; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { length = response.ContentLength; } } catch (WebException ex) { // Log exception and throw as for GET example above }}我在我们的Web服务的自动化测试中使用了这样的代码。



