码迷,mamicode.com
首页 > Web开发 > 详细

WebRequest 对象的使用

时间:2015-08-06 18:13:51      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

//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();
}
}

 

}

WebRequest 对象的使用

标签:

原文地址:http://www.cnblogs.com/bweb/p/4708685.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!