概述
后台代码:
调用:
//POST
IDictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("sql", strSql);
parameters.Add("rp", strSelectReplace);
string strResult = queryPlatDataOnlinePost(strUrl, parameters, 5000);
//方法
#region Post请求
private string queryPlatDataOnlinePost(string strUrl, IDictionary<string, string> parameters, int timeout){
try
{
if (string.IsNullOrEmpty(strUrl))
{
throw new ArgumentNullException("url");
}
HttpWebRequest request = WebRequest.Create(strUrl) as HttpWebRequest;
request.ServicePoint.Expect100Continue = false;
request.ServicePoint.UseNagleAlgorithm = false; //是否使用 Nagle 不使用 提高效率
//request.AllowWriteStreamBuffering = false; //数据是否缓冲 false 提高效率
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";//没效果
request.Accept = "text/plain;charset=utf-8"; //该编码有效,可解决乱码问题
request.Timeout = timeout;
Encoding requestEncoding = Encoding.GetEncoding("UTF-8");
//如果需要POST数据
if (!(parameters == null || parameters.Count == 0))
{
StringBuilder buffer = new StringBuilder();
int i = 0;
foreach (string key in parameters.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
}
i++;
}
byte[] data = requestEncoding.GetBytes(buffer.ToString());
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
//获取响应,并设置响应编码
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
//读取响应流
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string returnData = reader.ReadToEnd();
reader.Dispose();
response.Close();
return returnData;
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "alert", "alert('" + ex.Message + "') ", true);
}
return "";
}
#endregion
最后
以上就是彪壮八宝粥为你收集整理的asp.net 调用HTTP接口并使用post传递参数的全部内容,希望文章能够帮你解决asp.net 调用HTTP接口并使用post传递参数所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复