C#get ,post

(1)get

发送url请求

设置请求方式

设置请求内容格式

获得回应对象,接收流

读取流

  private string Get(string url)
        {
            string all = string.Empty;
            //发送请求
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "get";//设置方法
            request.ContentType = "text/html;charset=UTF-8";
            //获得响应
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //读取流
            Stream stream = response.GetResponseStream();
            StreamReader sr = new StreamReader(stream, Encoding.UTF8);
            all= sr.ReadToEnd();
            //关闭流
            stream.Close();
            sr.Close();
            return all;
        }

(2)post

发送url请求

设置请求方式

设置请求内容格式

设置请求内容长度(可以不设置)(长度是byte数组的长度,不是string类型的长度)

将post数据添加到请求流中(重中之重GetRequestStream())

接收回应对象,接收流

读取流

 public static string Post(string postdata, string url)
        {
            HttpWebResponse hw;
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";
            #region 添加Post 参数
            byte[] data = Encoding.UTF8.GetBytes(postdata);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);//将post对象放入请求流中
                reqStream.Close();
            }
            #endregion
            try
            {
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (WebException w)
            {
                hw = (HttpWebResponse)w.Response;
                StreamReader sr = new StreamReader(hw.GetResponseStream(), Encoding.UTF8, false);
                result = sr.ReadToEnd();
            }
            return result;
        }
时间: 2024-11-11 18:05:21