public static string HttpGet(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException exc) { response = (HttpWebResponse)exc.Response; } Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
/// <summary> /// 返回JSon数据 /// </summary> /// <param name="parameter">需要传递的数据,没有则传递null</param> /// <param name="Url">要提交的URL</param> /// <returns>返回的数据</returns> public static string GetResponseData(string parameter, string Url, RequestMethod method) { bool isWrite=false; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = method.ToString(); if (!String.IsNullOrEmpty(parameter)) { byte[] bytes = Encoding.UTF8.GetBytes(parameter); request.ContentLength = bytes.Length; request.ContentType = "text/plain"; Stream reqstream = request.GetRequestStream(); reqstream.Write(bytes, 0, bytes.Length); } request.ServicePoint.Expect100Continue = false; //声明一个HttpWebRequest请求 request.Timeout = 10 * 1000; //设置连接超时时间 request.Headers.Set("Pragma", "no-cache"); HttpWebResponse response = null; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException exc) { response = (HttpWebResponse)exc.Response; isWrite = true; } Stream streamReceive = response.GetResponseStream(); Encoding encoding = Encoding.UTF8; StreamReader streamReader = new StreamReader(streamReceive, encoding); string strResult = streamReader.ReadToEnd(); streamReceive.Dispose(); streamReader.Dispose(); if (isWrite) { WriteLog.Log("HttpWebRequest异常:" + strResult, "HttpWebRequest异常.txt"); WriteLog.Log("JSONData:" + parameter, "HttpWebRequest异常.txt"); WriteLog.Log("Url:" + Url, "HttpWebRequest异常.txt"); } return strResult; }