养生 装修 购物 美食 感冒 便秘 营销 加盟 小吃 火锅 管理 创业 搭配 减肥 培训 旅游

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

© 一点知识