博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
模拟Post请求
阅读量:5245 次
发布时间:2019-06-14

本文共 1777 字,大约阅读时间需要 5 分钟。

#region 向Url发送post请求 /// <summary> /// 向Url发送post请求 /// </summary> /// <param name="postData">发送数据</param> /// <param name="uriStr">接受数据的Url</param> /// <returns>返回网站响应请求的回复</returns> public static string RequestPost(string postData, string uriStr) { HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(uriStr); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] data = encoding.GetBytes(postData); requestScore.Method = "Post"; requestScore.ContentType = "application/x-www-form-urlencoded"; requestScore.ContentLength = data.Length; requestScore.KeepAlive = true; Stream stream = requestScore.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); HttpWebResponse responseSorce; try { responseSorce = (HttpWebResponse)requestScore.GetResponse(); } catch (WebException ex) { responseSorce = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示 } StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8); string content = reader.ReadToEnd(); requestScore.Abort(); responseSorce.Close(); responseSorce.Close(); reader.Dispose(); stream.Dispose(); return content; } #endregion

网站得到Post过来的数据:

/// <summary> /// 得到程序post过来的数据 /// </summary> /// <returns></returns> private string GetPostContent() { string postStr = string.Empty; Stream inputStream = Request.InputStream; int contentLength = Request.ContentLength; int offset = 0; if (contentLength > 0) { byte[] buffer = new byte[contentLength]; for (int i = inputStream.Read(buffer, offset, contentLength - offset); i > 0; i = inputStream.Read(buffer, offset, contentLength - offset)) { offset += i; } UTF8Encoding encoding = new UTF8Encoding(); postStr = encoding.GetString(buffer); } return postStr; }

转载于:https://www.cnblogs.com/zhangqs008/archive/2011/05/21/2341134.html

你可能感兴趣的文章
Google Guava学习笔记——简介
查看>>
历时八年,HTML5 标准终于完工了
查看>>
17.树的子结构
查看>>
D - Mike and strings
查看>>
C++:多维数组的动态分配(new)和释放(delete)
查看>>
c#基础学习(0806)之抽象类实现多态
查看>>
S5PV210根文件系统的制作(一)
查看>>
51NOD 1244 莫比乌斯函数之和
查看>>
[bzoj1923]外星千足虫[高斯消元]
查看>>
centos下同时启动多个tomcat
查看>>
slab分配器
查看>>
分析 PHP大马-php_mof SHELL
查看>>
TCP/IP
查看>>
[推荐] 协同滤波 —— Collaborative Filtering (CF)
查看>>
python中使用中文
查看>>
数据清洗
查看>>
Android 动态加载 (二) 态加载机制 案例二
查看>>
MVC5 + EF6 + Bootstrap3 (10) 数据查询页面
查看>>
Windows下的Eclipse启动出现:a java runtime environment(JRE) or java development kit(JDK) must be.......
查看>>
PLC 通讯
查看>>