模拟get请求并返回字符串
public static string HttpGet(Uri url) { string result = string.Empty; try { HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; webRequest.Method = "GET"; using (var response = webRequest.GetResponse()) { using (var sr = new StreamReader(response.GetResponseStream())) { result = sr.ReadToEnd(); } } } catch (Exception ex) { throw new Exception(ex.ToString()); } return result;
模拟post表单请求
public static string HttpPost(Uri url, string postData) { string result = string.Empty; try { var data = Encoding.ASCII.GetBytes(postData); WebRequest res = WebRequest.Create(url); res.ContentType = "application/x-www-form-urlencoded"; res.Method = "post"; res.UseDefaultCredentials = true; res.ContentLength = data.Length; var task = res.GetResponseAsync(); using (var stream = res.GetRequestStream()) { stream.Write(data, 0, data.Length); } WebResponse rep = task.Result; Stream respStream = rep.GetResponseStream(); using (StreamReader reader = new StreamReader(respStream, Encoding.Default)) { result = reader.ReadToEnd(); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return result; }
下载文件
public static string HttpGetFile(Uri url) { string result = string.Empty; WebResponse response; Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); try { HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest; webRequest.Method = "GET"; response = webRequest.GetResponse(); } catch (WebException ex) { response = ex.Response; return null; } using (var sr = new StreamReader(response.GetResponseStream(), encode)) { result = sr.ReadToEnd(); } return result; }
欢迎指错!