c#如何带Cookies进行http的Post和Get访问

 时间:2024-11-05 16:01:16

Post和get访问是网络编程常用的方法

工具/原料

vs2015

sharpdevelop

方法/步骤

1、打开vs,新建项目引用:usingSystem.Net.Http;usingSystem.Net;

c#如何带Cookies进行http的Post和Get访问

2、添加代码,代码如下,直接复制粘贴就可以用了

c#如何带Cookies进行http的Post和Get访问

3、publicstaticstr坡纠课柩ingHttpPost(stringurl,stringpostdata,惺绅寨瞀stringcookies){HttpWebRequestrequest=null;HttpWebResponseresponse=null;try{request=(HttpWebRequest)WebRequest.Create(url);request.Method="POST";byte[]data=Encoding.UTF8.GetBytes(postdata);request.ContentType="application/x-www-form-urlencoded";request.ServicePoint.ConnectionLimit=3000;request.UserAgent="Mozilla/5.0(WindowsNT6.1)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.83Safari/535.11";request.ContentLength=data.Length;request.Headers.Add("cookie",cookies);StreamnewStream=request.GetRequestStream();newStream.Write(data,0,data.Length);newStream.Close();response=(HttpWebResponse)request.GetResponse();StreamReaderreader=newStreamReader(response.GetResponseStream(),Encoding.Default);stringresult=reader.ReadToEnd();reader.Close();request.Abort();response.Close();returnresult;}catch(Exceptionex){if(request!=null)request.Abort();if(response!=null)response.Close();returnstring.Empty;}}

4、下面是get的代码咯悝滩镞privatestringHttpGetData(stringurl,stringcookies){Http友腆取缜WebRequestmyRequest=(HttpWebRequest)WebRequest.Create(url);myRequest.Headers.Add("cookie",cookies);myRequest.Method="GET";HttpWebResponsemyResponse=(HttpWebResponse)myRequest.GetResponse();StreamReaderreader=newStreamReader(myResponse.GetResponseStream(),Encoding.UTF8);stringcontent=reader.ReadToEnd();reader.Close();returncontent;}

逆战暮光古堡炼狱飞车飞天跳关卡法 小米视频如何取消红包挂件 花烛怎么科学护养 如何设置让windows xp电脑自动关机 宽带连接不上,提示错误720怎么解决
热门搜索
大主宰图片 拉拉电影 巧克力的图片 亚洲 图片另类欧美 印尼屠华图片