1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
using System; using System.IO; using System.Net; using System.Text; namespace w3cnet.Utils { /// <summary> /// Web请求相关 /// </summary> public class WebUtil { /// <summary> /// 获取公网url内容 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetPage(string url) { return RequestGet(url); } /// <summary> /// Post请求 /// </summary> /// <returns></returns> public static string RequestGet(string url) { //请求 var request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 3600000; //3600秒 //接收 var response = request.GetResponse(); var responseStream = response.GetResponseStream(); if (responseStream != null) { var reader = new StreamReader(responseStream); var result = reader.ReadToEnd(); reader.Close(); response.Close(); return result; } return string.Empty; } /// <summary> /// Post请求 /// </summary> /// <returns></returns> public static string RequestPost(string url, string data = null, Encoding encoding = null) { if (encoding == null) encoding = Encoding.UTF8; //请求 var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; //参数 if (!string.IsNullOrEmpty(data)) { var byteArray = encoding.GetBytes(data); request.ContentLength = byteArray.Length; var requestStream = request.GetRequestStream(); requestStream.Write(byteArray, 0, byteArray.Length); requestStream.Close(); } //接收 var response = request.GetResponse(); var responseStream = response.GetResponseStream(); if (responseStream != null) { var reader = new StreamReader(responseStream, encoding); var result = reader.ReadToEnd(); reader.Close(); response.Close(); return result; } return string.Empty; } } } |