模拟Post请求

简介:

#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; }

目录
相关文章
|
3月前
|
网络协议 API C#
C# 中模拟 POST 和 GET 请求的原理与实践
【1月更文挑战第4天】在现代网络应用中,HTTP请求是客户端与服务器交互的基础。其中,GET和POST是最常用的两种请求方法。本文将介绍如何使用C#语言模拟这两种请求,并解释其背后的工作原理。我们将利用.NET框架中的HttpClient类来发送请求,并处理服务器的响应。通过本文,读者将能够理解HTTP请求的基本构成,学会在C#中编写代码来模拟这些请求,进而在开发过程中实现与Web服务的交互。
|
5月前
|
JSON 小程序 前端开发
小程序模拟请求服务器json数据
小程序模拟请求服务器json数据
183 0
|
2月前
|
缓存 安全 API
Post请求和get请求的区别是什么?
Post请求和get请求的区别是什么?
|
8月前
|
安全 前端开发 JavaScript
【GET请求和POST请求区别。】
GET请求和POST请求是HTTP协议中最常见的两种请求方法,它们在客户端向服务器发送请求时有着不同的特点和用途。
78 0
|
8月前
|
JSON 数据格式
axios 请求数据(Post,Get)细节
axios 请求数据(Post,Get)细节
61 0
|
9月前
|
XML 前端开发 JavaScript
教你怎么用最原始的ajax发送post请求和get请求
教你怎么用最原始的ajax发送post请求和get请求
186 0
|
11月前
|
XML JSON 安全
get请求和post请求的区别以及常用请求方式
get请求和post请求的区别以及常用请求方式
|
JSON 缓存 前端开发
【Ajax入门技术】如何设置请求头 体 ,利用ajax进行取消请求数据操作,解决重复请求问题,请求超时网络异常以及获取json数据
【Ajax入门技术】如何设置请求头 体 ,利用ajax进行取消请求数据操作,解决重复请求问题,请求超时网络异常以及获取json数据
238 0
【Ajax入门技术】如何设置请求头 体 ,利用ajax进行取消请求数据操作,解决重复请求问题,请求超时网络异常以及获取json数据
|
数据采集 Python
爬虫第二次笔记 解编码 使用get请求方式和post请求方式
爬虫第二次笔记 解编码 使用get请求方式和post请求方式
204 0
爬虫第二次笔记 解编码 使用get请求方式和post请求方式
|
JSON 前端开发 数据格式
学习AJAX必知必会(2)~Ajax基本使用,设置请求行、请求体、请求头,服务端响应JSON数据
学习AJAX必知必会(2)~Ajax基本使用,设置请求行、请求体、请求头,服务端响应JSON数据
575 0