您的位置:首页 > 理论基础 > 计算机网络

HttpWebRequest使用的注意事项

2015-04-25 11:02 507 查看
private void button33_Click(object sender, EventArgs e)

{

//下面这一步应该没有去连接远程服务器,因为地址如果错误,这一步没有出现异常



HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create("http://localhost:8081/weixin01/servlet/CoreServlet");

hwr.CookieContainer = cc;

hwr.ContentType = "application/x-www-form-urlencoded";

hwr.Method = "POST";

hwr.Timeout = 30 * 1000;

hwr.KeepAlive = true;

hwr.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; BTRS124342; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2)";

hwr.Referer = "http://localhost:8080/weixin01/servlet/CoreServlet";

Encoding encoding = Encoding.GetEncoding("utf-8");

byte[] data = encoding.GetBytes("a=1");

//测试证明这一步会连接远程服务器,如果地址簿存存在,会报无法连接远程服务器的异常



Stream myRequestStream = hwr.GetRequestStream();

myRequestStream.Write(data, 0, data.Length);

myRequestStream.Close();

//测试证明在执行到下面红色这一行时候才会跳转到服务端后台的doPost方法之中



HttpWebResponse myHttpWebResponse = (HttpWebResponse)hwr.GetResponse();

Stream myResponseStream = myHttpWebResponse.GetResponseStream();

StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gbk"));

string outhtml = myStreamReader.ReadToEnd();

//把数据从HttpWebResponse的Response流中读出

myStreamReader.Close();

myResponseStream.Close();

myHttpWebResponse.Close();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: