HttpWebRequest get/post方法实现
get请求url
#region GetHttp请求 /// <summary> /// GetHttp请求 /// </summary> /// <param name="url">GetUrl</param> /// <returns></returns> public static string HttpWebResponse_Get(string url) { string strRet = null; try { string strUrl = url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl); request.Timeout = 2000; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); System.IO.Stream resStream = response.GetResponseStream(); Encoding encode = System.Text.Encoding.UTF8; StreamReader readStream = new StreamReader(resStream, encode); Char[] read = new Char[256]; int count = readStream.Read(read, 0, 256); while (count > 0) { String str = new String(read, 0, count); strRet = strRet + str; count = readStream.Read(read, 0, 256); } resStream.Close(); } catch (Exception e) { } return strRet; } #endregion
Post请求
#region PostHttp请求 /// <summary> /// PostHttp请求 /// </summary> /// <param name="postData">post数据</param> /// <param name="url">postUrl</param> public static string HttpWebResponse_Post(string postData, string url) { string result = null; try { //string postData = "{\"tableName\":\"" + tableName + "\",\"tableId\": \"" + tableId + "\"}"; Uri uri = new Uri(url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = bytes.Length; Stream writeStream = request.GetRequestStream(); writeStream.Write(bytes, 0, bytes.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8)) { result = readStream.ReadToEnd(); readStream.Close(); } } writeStream.Close(); return result; } catch (Exception) { } return result; } #endregion