1.Post主动发送Json格式数据
/// <summary> /// 指定Post地址使用Get 方式获取全部字符串 /// </summary> /// <param name="url">请求后台地址</param> /// <param name="content">Post提交数据内容(utf-8编码的)</param> /// <returns>结果</returns> public static string DataPost(string url, string content, HttpResponseBase Response) { //申明一个容器result接收数据 string result = ""; try { //首先创建一个HttpWebRequest,申明传输方式POST HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = "application/json"; //添加POST参数 byte[] data = Encoding.UTF8.GetBytes(content); req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } //申明一个容器resp接收返回数据 HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //获取响应内容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); var stringstr = "<stream><return_code>SUCCESS</return_code></stream>"; Response.Write(stringstr); Response.End(); } } catch (Exception ex) { var stringstr = "<stream><return_code>FAIL</return_code></stream>"; Response.Write(stringstr); Response.End(); } return result; }
2.主动接收通知并且返回发送给对方成功或失败
public static string GetResult(HttpRequestBase Request, HttpResponseBase Response) { var xmlData = ""; try { if (Request.RequestType == "POST") { //接收并读取POST过来的XML文件流 StreamReader reader = new StreamReader(Request.InputStream); xmlData = reader.ReadToEnd(); var stringstr = "<stream><return_code>SUCCESS</return_code></stream>"; Response.Write(stringstr); Response.End(); } } catch (Exception ex) { var stringstr = "<stream><return_code>FAIL</return_code></stream>"; Response.Write(stringstr); Response.End(); } return xmlData; }