C# post json和接收json
HttpHelper
using MyCLib; using System; using System.Data; using System.Data.OleDb; using System.Globalization; using System.IO; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using FileEncoding; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; using Newtonsoft.Json; using System.Collections.Generic; using System.Net; public class HttpHelper { public static JObject PostJson(string url, Dictionary<string, object> param) { string paramStr = JsonConvert.SerializeObject(param); byte[] data = System.Text.Encoding.UTF8.GetBytes(paramStr); var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/json"; Stream newStream = request.GetRequestStream(); newStream.Write(data, 0, data.Length); newStream.Close(); request.ServicePoint.Expect100Continue = false; request.ProtocolVersion = HttpVersion.Version11; var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return JObject.Parse(responseString); } return null; } public static JObject GetJson(string url) { var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { return JObject.Parse(responseString); } return null; } }
p1:post json
Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("id", 1); dict.Add("name", "张三"); dict.Add("age", 100); string url = MyCLib.StrClass.GetDomain() + "http://www.ceshi.com/p2.aspx"; string json = HttpHelper.PostJson(url, dict).ToString(); Response.Write(json);
p2:接收 json
var sr = new StreamReader(System.Web.HttpContext.Current.Request.InputStream); var stream = sr.ReadToEnd(); var dict = JsonConvert.DeserializeObject<Dictionary<object, object>>(stream); dict.Add("time", DateTime.Now.ToString()); string json = JsonConvert.SerializeObject(dict); Response.Write(json); Response.End();
//成功一定有方法,失败一定有原因。