需要引入using System.IO;using System.Net;
public string GETs(string URL) { //创建httpWebRequest对象 HttpWebRequest Request = (HttpWebRequest)WebRequest.CreateHttp(URL); //设置属性,初始化HttpWebRequest对象 Request.Method = "GET"; Request.Timeout = 30000; Request.ContentType = "application/x-www-form-urlencoded"; // 读取服务器的返回信息 HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); //将信息流转换为字符串 StreamReader Reader = new StreamReader(Response.GetResponseStream(), Encoding.UTF8); var Datas = Reader.ReadToEnd();//以字符串形式返回信息流 Response.Close();//关闭响应释放资源 Reader.Close();//关闭流,释放资源 return Datas; } public string POSTs(string URL, string DataName, string DataValues) { //创建httpWebRequest对象 HttpWebRequest Request = (HttpWebRequest)WebRequest.CreateHttp(URL); //设置属性,初始化HttpWebRequest对象 Request.Method = "POST"; Request.Timeout = 30000; Request.ContentType = "application/x-www-form-urlencoded"; //附加要POST给服务器的数据到HttpWebRequest对象 DataName是键 DataValues是值 //如果传多值GetBytes()方法中最终字符串形式为:Key1=Value1&Key2=Value2&Key3=Value3 Stream reqStream = Request.GetRequestStream(); byte[] byteArray = Encoding.UTF8.GetBytes(DataName + "=" + DataValues); reqStream.Write(byteArray, 0, byteArray.Length); reqStream.Close(); //读取服务器的返回信息 HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); //将信息流转换为字符串 StreamReader Reader = new StreamReader(Response.GetResponseStream(), Encoding.UTF8); var Datas = Reader.ReadToEnd();//以字符串形式返回信息流 Response.Close();//关闭响应释放资源 Reader.Close();//关闭流,释放资源 return Datas; }
ps:参考一下内容
https://www.cnblogs.com/hudean/p/11721634.html
https://www.cnblogs.com/zhuji/p/9335355.html
如有疑问可以评论指出