public string Post_Http(string url, string postData) { string strResult = ""; try { //将字符串参数 转换成字节数组 便于写入流 byte[] byteData = Encoding.GetEncoding("utf-8").GetBytes(postData); //创建请求实例 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); //设置请求方式 myRequest.Method = "POST"; //设置所发送的请求数据的内容类型 myRequest.ContentType = "application/x-www-form-urlencoded"; //设置所发送的请求数据的内容长度。 myRequest.ContentLength = byteData.Length; //获得请求的流 Stream requestStream = myRequest.GetRequestStream(); //将内容写入请求流 requestStream.Write(byteData, 0, byteData.Length); requestStream.Close(); //得到请求相应的内容 HttpWebResponse HttpWResp = (HttpWebResponse)myRequest.GetResponse(); //将得到的数据写入stream中 Stream streamResp = HttpWResp.GetResponseStream(); // 初始化一个读取的文件流对象 StreamReader sr = new StreamReader(streamResp, Encoding.UTF8); StringBuilder strBuilder = new StringBuilder(); //读取数据 while (-1 != sr.Peek()) { strBuilder.Append(sr.ReadLine()); } strResult = strBuilder.ToString(); HttpWResp.Close(); sr.Close(); } catch (Exception ee) { strResult = ee.Message; } return strResult; }
2.get方式
public string Get_Http(string tUrl) { string strResult; try { //实例化WebRequest对象 静态 HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(tUrl); hwr.Method = "GET"; //设置请求前超时前的时间长度 毫秒 hwr.Timeout = 20000; //20s //重写,返回对 Internet 请求的响应。 hwr HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse(); //返回用于将数据写入 Internet 资源的 System.IO.Stream。 Stream myStream = hwrs.GetResponseStream(); //初始化一个流对象并 设置初始化时的编码格式 StreamReader sr = new StreamReader(myStream, Encoding.UTF8); StringBuilder sb = new StringBuilder(); //判断是否有值 -1没有 while (-1 != sr.Peek()) { // 从当前流中读取一行并将数据作为字符串返回。ReadLine() //追加到StringBuilder上 sb.Append(sr.ReadLine() + "\r\n"); } strResult = sb.ToString(); //关闭对象 sr.Close(); hwrs.Close(); } catch (Exception ee) { strResult = ee.Message; } //返回结果 return strResult; }
时间: 2024-10-23 23:04:54