KeyValuePair<string, string>

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

KeyValuePair<string, string>的相关文章

Dictionary&lt;string, string&gt; 排序

.net framework 2.0 版 Dictionary<string, string> collection = new Dictionary<string, string> (); collection.Add("key3","value3"); collection.Add("key1","value1"); collection.Add("key4","val

从为什么String=String谈到StringBuilder和StringBuffer

前言 有这么一段代码 1 public class TestMain 2 { 3 public static void main(String[] args) 4 { 5 String str0 = "123"; 6 String str1 = "123"; 7 System.out.println(str0 == str1); 8 } 9 } 运行结果是什么?答案当然是true.对,答案的确是true,但是这是为什么呢?很多人第一反应肯定是两个“123”的Stri

(后缀数组)HDU 6194-string string string

string string string Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 774    Accepted Submission(s): 225 Problem Description Uncle Mao is a wonderful ACMER. One day he met an easy problem, but Un

hdu 6194 string string string(后缀数组)

题目链接:hdu 6194 string string string 题意: 给你一个字符串,给你一个k,问你有多少个子串恰好在原串中出现k次. 题解: 后缀数组求出sa后,用height数组的信息去找答案. 每次用k长度的区间去卡height数组,求出该区间的lcp. 该区间的贡献就是ans=lcp-max(height[i],height[i+k]). 如果ans<=0,就不贡献. 比如 2 aaa 后缀数组为: 1 a 2 aa 3 aaa height为 0,1,2 现在扫到[1,2],

List&amp;lt;Map&amp;lt;String, String&amp;gt;&amp;gt; 开启 Map&amp;lt;String, List&amp;lt;String&amp;gt;&amp;gt;

将List变成Map结构体,下面的文字是没有水平! 写作方法传送前土壤很长一段时间.我不知道有没有好的解决办法.我们也希望提供! Map<String, String> map1 = new HashMap<String, String>(); map1.put("a", "1"); map1.put("b", "3"); map1.put("c", "5");

Struts2标签遍历List&lt;Map&lt;String, String&gt;&gt;

import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private List<Map<String, String>> list; @Override

The constructor User.Student(String, String, String) is not visible

项目:蒙文词语检索 日期:2016-05-01 提示:The constructor User.Student(String, String, String) is not visible 出处:Dbdao.insert(new Student("Achilles", "Male", "14")); 解决方法: 原代码:Student(String Name, String Sex, String Age) 修改成:public Student(

Map&lt;String, String&gt;的数据处理以及ListView的适配器

Map<String, String> map = new HashMap<String, String>(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); //第一种:普遍使用,二次取值 System.out.println("通过Ma

使用System.IO.Combine(string path1, string path2, string path3)四个参数的重载函数提示`System.IO.Path.Combine(string, string, string, string)&#39; is inaccessible due to its protection level

今天用Unity5.5.1开发提取Assets目录的模块,使用时采用System.IO.Path.Combine(string, string, string, string)函数进行路径生成 明明是公有函数,为何会报错,奇了怪了 有谁知道什么原因?欢迎交流 ....... ... 重新打开了一下 ,可以了.版本原因 使用System.IO.Combine(string path1, string path2, string path3)四个参数的重载函数提示`System.IO.Path.Co