利用HttpWebRequest通过POST Json数据在.net后台实现不同平台间的数据传输
/// <summary> /// 返回JSon数据 /// </summary> /// <param name="JSONData">要处理的JSON数据</param> /// <param name="Url">要提交的URL</param> /// <returns>返回的JSON处理字符串</returns> public string GetResponseData(string JSONData,string Url) {byte[] bytes = Encoding.UTF8.GetBytes(JSONData) HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentLength = bytes.Length; request.ContentType = "text/xml"; Stream reqstream = request.GetRequestStream(); reqstream.Write(bytes, 0, bytes.Length); //声明一个HttpWebRequest请求 request.Timeout = 90000; //设置连接超时时间 request.Headers.Set("Pragma", "no-cache"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream streamReceive = response.GetResponseStream(); Encoding encoding = Encoding.UTF8; StreamReader streamReader = new StreamReader(streamReceive, encoding); string strResult = streamReader.ReadToEnd(); streamReceive.Dispose(); streamReader.Dispose(); return strResult; }
如果不通过request.write()的方式向接口post数据,将request.ContentLength属性设置为0,让后去掉request.write()方法即可!
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。