static int _timeout = 100000; #region CUP Method /// <summary> /// 请求与响应的超时时间 /// </summary> static public int Timeout { get { return _timeout; } set { _timeout = value; } } /// <summary> /// 执行HTTP POST请求。 /// </summary> /// <param name="url">请求地址</param> /// <param name="parameters">请求参数</param> /// <returns>HTTP响应</returns> static public string DoPost(string url, IDictionary<string, string> parameters) { string result = string.Empty; try { HttpWebRequest req = GetWebRequest(url, "POST"); NetworkCredential proxyCredential = new NetworkCredential(); proxyCredential.UserName = proxyUserName; proxyCredential.Password = proxyPassword; req.Credentials = proxyCredential; WebProxy proxy = new WebProxy(proxyIpAddress); proxy.Credentials = proxyCredential; req.Proxy = proxy; var httpClientHandler = new HttpClientHandler() { Proxy = proxy, }; httpClientHandler.PreAuthenticate = true; httpClientHandler.UseDefaultCredentials = false; httpClientHandler.Credentials = proxyCredential; var client = new HttpClient(handler: httpClientHandler, disposeHandler: true); var res = client.GetStringAsync(url).Result; req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters)); Stream reqStream = req.GetRequestStream(); reqStream.Write(postData, 0, postData.Length); reqStream.Close(); HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); result = GetResponseAsString(rsp, encoding); } catch (Exception ex) { result = string.Format("Request exception:{0}, please try again later.", ex.Message); } return result; } /// <summary> /// 执行HTTP GET请求。 /// </summary> /// <param name="url">请求地址</param> /// <param name="parameters">请求参数</param> /// <returns>HTTP响应</returns> static public string DoGet(string url, IDictionary<string, string> parameters) { string result = string.Empty; try { if (parameters != null && parameters.Count > 0) { if (url.Contains("?")) { url = url + "&" + BuildQuery(parameters); } else { url = url + "?" + BuildQuery(parameters); } } HttpWebRequest req = GetWebRequest(url, "GET"); req.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; HttpWebResponse rsp = (HttpWebResponse)req.GetResponse(); Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet); result = GetResponseAsString(rsp, encoding); } catch (Exception ex) { result = string.Format("Request exception:{0}, please try again later.", ex.Message); } return result; } static public HttpWebRequest GetWebRequest(string url, string method) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ServicePoint.Expect100Continue = false; req.Method = method; req.KeepAlive = true; //req.UserAgent = "Aop4Net"; req.Timeout = _timeout; return req; } /// <summary> /// 把响应流转换为文本。 /// </summary> /// <param name="rsp">响应流对象</param> /// <param name="encoding">编码方式</param> /// <returns>响应文本</returns> static public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding) { StringBuilder result = new StringBuilder(); Stream stream = null; StreamReader reader = null; try { // 以字符流的方式读取HTTP响应 stream = rsp.GetResponseStream(); reader = new StreamReader(stream, encoding); // 按字符读取并写入字符串缓冲 int ch = -1; while ((ch = reader.Read()) > -1) { // 过滤结束符 char c = (char)ch; if (c != ‘\0‘) { result.Append(c); } } } finally { // 释放资源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (rsp != null) rsp.Close(); } return result.ToString(); } /// <summary> /// 组装普通文本请求参数用于post请求 /// </summary> /// <param name="parameters">Key-Value形式请求参数字典</param> /// <returns>URL编码后的请求数据</returns> static public string BuildQuery(IDictionary<string, string> parameters) { StringBuilder postData = new StringBuilder(); bool hasParam = false; IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator(); while (dem.MoveNext()) { string name = dem.Current.Key; string value = dem.Current.Value; // 忽略参数名或参数值为空的参数 if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value)) { if (hasParam) { postData.Append("&"); } postData.Append(name); postData.Append("="); postData.Append(Uri.EscapeDataString(value)); hasParam = true; } } return postData.ToString(); } #endregion
#region Parse Dictionary #region Dictionary Parse To String /// <summary> /// Dictionary Parse To String /// </summary> /// <param name="parameters">Dictionary</param> /// <returns>String</returns> static public string ParseToString(IDictionary<string, string> parameters) { IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters); IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator(); StringBuilder query = new StringBuilder(""); while (dem.MoveNext()) { string key = dem.Current.Key; string value = dem.Current.Value; if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) { query.Append(key).Append("=").Append(value).Append("&"); } } string content = query.ToString().Substring(0, query.Length - 1); return content; } #endregion #region String Parse To Dictionary /// <summary> /// String Parse To Dictionary /// </summary> /// <param name="parameter">String</param> /// <returns>Dictionary</returns> static public Dictionary<string, string> ParseToDictionary(string parameter) { try { String[] dataArry = parameter.Split(‘&‘); Dictionary<string, string> dataDic = new Dictionary<string, string>(); for (int i = 0; i <= dataArry.Length - 1; i++) { String dataParm = dataArry[i]; int dIndex = dataParm.IndexOf("="); if (dIndex != -1) { String key = dataParm.Substring(0, dIndex); String value = dataParm.Substring(dIndex + 1, dataParm.Length - dIndex - 1); dataDic.Add(key, value); } } return dataDic; } catch { return null; } } #endregion #endregion
原文地址:https://www.cnblogs.com/hofmann/p/11532253.html
时间: 2024-10-11 09:16:27