public string GET2(string URL) { HttpWebRequest Request = (HttpWebRequest)WebRequest.CreateHttp(URL);//创建httpWebRequest对象 //设置属性,初始化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 as1 = Reader.ReadToEnd();//以字符串形式返回信息流 Response.Close();//关闭响应释放资源 Reader.Close();//关闭流,释放资源 return as1; } public string POST2(string URL,string DataJSON) { HttpWebRequest Request = (HttpWebRequest)WebRequest.CreateHttp(URL);//创建httpWebRequest对象 //设置属性,初始化HttpWebRequest对象 Request.Method = "POST"; Request.Timeout = 30000; Request.ContentType = "application/x-www-form-urlencoded"; // 附加要POST给服务器的数据到HttpWebRequest对象 json是键 DataJSON是值 Stream reqStream = Request.GetRequestStream(); byte[] byteArray = Encoding.UTF8.GetBytes("json=" + DataJSON);//("json=" + DataJSON+"&name=‘123456‘")传多值 reqStream.Write(byteArray, 0, byteArray.Length); reqStream.Close(); // 读取服务器的返回信息 HttpWebResponse Response = (HttpWebResponse)Request.GetResponse(); //将信息流转换为字符串 StreamReader Reader = new StreamReader(Response.GetResponseStream(), Encoding.ASCII); var as1 = Reader.ReadToEnd();//以字符串形式返回信息流 Response.Close(); Reader.Close(); return as1; }
需要引入using System.IO;using System.Net;