秀色网,大连火车站时刻表,落水走光
使用httpwebrequest等http相关类,可以在应用程序中或者网站中模拟浏览器发送post请求,在请求带入相应的post参数值,而后请求回远程网页信息。实现这一功能也很简单,主要是依靠httpwebrequest、httpwebresponse、stream等几个类来完成。
首先来看下msdn上对这几个类的定义:
httpwebrequest类:提供用于在预先定义的属性和方法支持webrequest和用于附加属性和方法,使用户直接使用http服务器进行交互。
httpwebresponse类:包含对webresponse类的属性和方法的http特定用法的支持。该httpwebresponse类用于构建发送http请求http独立的客户端应用程序和接收http响应。
stream类:所有流的抽象基类。流是字节序列的抽象,例如文件,输入/输出设备,进程间通信管道或tcp / ip套接字。的类及其派生类提供这些不同类型的输入和输出的的一般视图,并分离从操作系统的具体细节和基础设备编程器。
下面直接贴代码了,已经将该功能封装成一个方法。
/// <summary> /// 以post方式抓取远程页面内容 /// </summary> /// <param name="postdata">参数列表</param> public static string post_http(string url, string postdata, string encodetype) { string strresult = null; try { encoding encoding = encoding.getencoding(encodetype); byte[] post = encoding.getbytes(postdata); httpwebrequest myrequest = (httpwebrequest)webrequest.create(url); myrequest.method = "post"; myrequest.contenttype = "application/x-www-form-urlencoded"; myrequest.contentlength = post.length; stream newstream = myrequest.getrequeststream(); newstream.write(post, 0, post.length); //设置post newstream.close(); httpwebresponse myresponse = (httpwebresponse)myrequest.getresponse(); streamreader reader = new streamreader(myresponse.getresponsestream(), encoding.default); strresult = reader.readtoend(); } catch (exception ex) { strresult = ex.message; } return strresult; }
备注:此文章转载自。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论