C# 实现Get/Post请求
/// <summary> /// Get请求 /// </summary> /// <param name="url">请求url</param> /// <returns></returns> public static string Get(string url) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); if (req == null || req.GetResponse() == null) return string.Empty; HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); if (resp == null) return string.Empty; using (Stream stream = resp.GetResponseStream()) { //获取内容 using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } /// <summary> /// Post请求 /// </summary> /// <param name="url"></param> /// <param name="postData"></param> /// <returns></returns> private static string Post(string url, object postData) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); if (req == null) return string.Empty; req.Method = "POST"; req.ContentType = "application/json"; req.Timeout = 15000; byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(postData)); //注意:无需手动指定长度 (否则可能会报流未处理完就关闭的异常,因为ContentLength时候会比真实post数据长度大) //req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); if (resp == null) return string.Empty; using (Stream stream = resp.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { return reader.ReadToEnd(); } } }