标签:
//url(请求的地址);postData(参数)
string HttpPost(string uri, string postData)
{
WebRequest webRequest = WebRequest.Create(uri);
webRequest.ContentType = "application/x-www-form-urlencoded"; // 设置请求的参数形式
webRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(postData); //指定编码格式
webRequest.ContentLength = bytes.Length; // 设置请求参数的长度.
Stream inStream = null;
try
{
inStream = webRequest.GetRequestStream(); //取得发向服务器的流
inStream.Write(bytes, 0, bytes.Length); //发送
}
catch (WebException ex)
{
return ex.Message.ToString();
}
finally
{
if (inStream != null)
{
inStream.Close();
}
}
StreamReader readStream = null;
try
{
WebResponse webResponse = webRequest.GetResponse(); // 等待返回结果
if (webResponse == null)
{
return null;
}
readStream = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8);
return readStream.ReadToEnd().Trim();
}
catch (WebException ex)
{
return ex.Message.ToString();
}
finally
{
if (readStream != null)
{
readStream.Close();
}
}
}
标签:
原文地址:http://www.cnblogs.com/bweb/p/4708685.html