KeyValuePair<string, string>
static int _timeout = ; #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, , 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 > )
{
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 = -;
while ((ch = reader.Read()) > -)
{
// 过滤结束符
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(, query.Length - ); 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 = ; i <= dataArry.Length - ; i++)
{
String dataParm = dataArry[i];
int dIndex = dataParm.IndexOf("=");
if (dIndex != -)
{
String key = dataParm.Substring(, dIndex);
String value = dataParm.Substring(dIndex + , dataParm.Length - dIndex - );
dataDic.Add(key, value);
}
} return dataDic;
}
catch
{
return null;
}
}
#endregion #endregion
KeyValuePair<string, string>的更多相关文章
- C#基础总结之五Dictionary<string, string[]>和while循环
#region 第五天作业 名片集(01) //Dictionary<string, string[]> PersonCard = new Dictionary<string, st ...
- Dictionary<string, string> 排序
.net framework 2.0 版 Dictionary<string, string> collection = new Dictionary<string, string& ...
- 遍历 SortedList<string, string> 中的值(可用于datatable转json)
SortedList<string, string> STK = new SortedList<string, string>();STK.Add("1", ...
- Dictionary<string, string>是一个泛型使用说明
Dictionary<string, string>是一个泛型使用说明 Posted on 2010-08-05 15:03 moss_tan_jun 阅读(2273) 评论(0) 编辑 ...
- 入门:Java Map<String,String>遍历及修改
重点:在使用Map时注意key-value,key用于检索value的内容. 在正常情况下,可以不允许重复:在java中分为2中情况,一是内存地址重复,另一个是不同的地址但内容相等. 在使用Map是一 ...
- 关于 Dictionary<string,string>,和List<T>在View的使用
在MVC中Dictionary<string,string>如何应用到View页面中呢,例: <input type="text" name=key value= ...
- alibaba fastjson List<Map<String, String>>2Str
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; impo ...
- getParameterMap()的返回值为Map<String, String[]>,从其中取得请求参数转为Map<String, String>的方法如下:
直接遍历报错:[Ljava.lang.String;@44739f3f Map<String, String> tempMap = new HashMap<String, Strin ...
- The constructor User.Student(String, String, String) is not visible
项目:蒙文词语检索 日期:2016-05-01 提示:The constructor User.Student(String, String, String) is not visible 出处:Db ...
随机推荐
- ROS Topic 常用指令
rostopic list rosnode list一樣,就是列出目前運行中的topic有哪些. rostopic echo <topic_name> 接下來這個指令比較重要啦,就是去監聽 ...
- 动态连通性问题——算法union-find
问题定义:问题的输入是一列整数对,其中每个整数都表示一个某种类型的对象,一对整数p,q可以被理解为"p和q是相连的".我们假设“相连”是一种对等的关系. 这也意味着它具有: 1.自 ...
- 重读APUE(7)-link/unlink与mkdir/rmdir
link–用于创建一个现有文件的链接:实际上是新建一个目录项,指向当前文件的i节点: unlink–用于删除一个现有文件的连接:实际上是对引用i节点的目录项进行删除,并且对链接计数-1:系统会检查文件 ...
- matplotlib画图报错This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
之前用以下代码将实验结果用matplotlib show出来 plt.plot(np.arange(len(aver_reward_list)), aver_reward_list) plt.ylab ...
- elasticsearch-6.4.3 集群搭建
1.准备三台服务器,已安装好es. 2.修改服务集群配置如下 使用命令: vi elasticsearch.yml 如下: cluster.name: myes ###保证三台服务器节点集群名称相同 ...
- How To Display Variable Value In View?
How To Display Variable Value In View? There are several ways. For example simply using @ like this: ...
- PHP魔术方法和魔法变量详解
一.魔术常量 __LINE__ 文件中的当前行号.__FILE__ 文件的完整路径和文件名.如果用在被包含文件中,则返回被包含的文件名. 自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对 ...
- 【java】[sql]使用Java程序向MySql数据库插入一千万条记录,各种方式的比较,最后发现insert批量插入方式对效率提升最明显
我的数据库环境是mysql Ver 14.14 Distrib 5.6.45, for Linux (x86_64) using EditLine wrapper 这个数据库是安装在T440p的虚拟机 ...
- JAVA踩坑录
以前踩了很多坑,大多忘了.现在踩了坑,想起了一定记下来. 1. 字符串分割,这种工具类,首次使用一定要先看一眼,不然跳坑 commons-lang StringUtils.split分割时会去掉空串: ...
- 假如React没了JSX
如题,想必React大家早已不陌生,而React里面的JSX都是玩的得心应手了,但是假如说React里面没有了React那会是一种什么样的情形呢,我们来简单的看一下. 首先我们来实现一个简单的list ...