如何用C# .NEt开发基于http的接口,只支持post方式传参,除webservice以外,谁能给个例子,万分感谢!
1个回答
展开全部
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
/// <summary>
/// 创建POST方式的<a href="https://www.baidu.com/s?wd=HTTP%E8%AF%B7%E6%B1%82&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1d9uWRzuH7-uHb4PHmsPy7b0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EPjcYPHnvrjR1PjcvPHn1njbz" target="_blank" class="baidu-highlight">HTTP请求</a>
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
/// <param name="timeout">请求的超时时间</param>
/// <returns></returns>
public static string PostHttpResponse(string url, Dictionary<string, string> parameters,
int? timeout)
{
try
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebRequest request = WebRequest.Create(url) 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";
request.UserAgent = DefaultUserAgent;
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
else
{
request.Timeout = 20000;
}
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)
{
MessageUtil.ShowWarning(ex.Message);
}
return "";
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询