發(fā)布時間:2020-08-06 16:08 作者:獨孤劍 閱讀:2278
/// <summary> /// Get 數(shù)據(jù) /// </summary> /// <param name="url">目標(biāo)Url</param> /// <returns></returns> public static string GetData(string url) { try { string result = ""; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Method = "Get"; HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { result = sr.ReadToEnd(); } httpWebResponse.Close(); httpWebRequest.Abort(); return result; } catch { throw; } } /// <summary> /// Post 數(shù)據(jù) /// </summary> /// <param name="url">目標(biāo)Url</param> /// <returns></returns> public static string PostData(string url) { try { string result = ""; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; //httpWebRequest.Timeout = 20000; HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"))) { result = sr.ReadToEnd(); } httpWebResponse.Close(); httpWebRequest.Abort(); return result; } catch { throw; } } /// <summary> /// Post 數(shù)據(jù) /// </summary> /// <param name="url">目標(biāo)Url</param> /// <param name="data">發(fā)送數(shù)據(jù)</param> /// <returns></returns> public static string PostData(string url, string data) { try { string result = ""; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; //httpWebRequest.Timeout = 20000; // byte[] buffer = Encoding.Default.GetBytes(HttpUtility.UrlEncode("username=test1&password=123456")); // byte[] buffer = Encoding.UTF8.GetBytes("{\"username\":\"test1\",\"password\":\"123456\"}"); byte[] buffer = Encoding.UTF8.GetBytes(data); httpWebRequest.ContentLength = buffer.Length; Stream requestStream = httpWebRequest.GetRequestStream(); requestStream.Write(buffer, 0, buffer.Length); requestStream.Close(); HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream())) { result = sr.ReadToEnd(); } httpWebResponse.Close(); httpWebRequest.Abort(); return result; } catch { throw; } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞