post方法

 1 CookieContainer cookie = new CookieContainer();
 2 private string HttpPost(string Url, string postDataStr)
 3         {
 4             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
 5             request.Method = "POST";
 6             request.ContentType = "application/x-www-form-urlencoded";
 7             request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
 8             request.CookieContainer = cookie;
 9             Stream myRequestStream = request.GetRequestStream();
10             StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
11             myStreamWriter.Write(postDataStr);
12             myStreamWriter.Close();
13  
14             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
15  
16             response.Cookies = cookie.GetCookies(response.ResponseUri);
17             Stream myResponseStream = response.GetResponseStream();
18             StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
19             string retString = myStreamReader.ReadToEnd();
20             myStreamReader.Close();
21             myResponseStream.Close();
22  
23             return retString;
24         }

在post的时候有时也用的到cookie,像登录163发邮件时候就需要发送cookie,所以在外部一个cookie属性随时保存 CookieContainer cookie = new CookieContainer();

!注意:有时候请求会重定向,但我们就需要从重定向url获取东西,像QQ登录成功后获取sid,但上面的会自动根据重定向地址跳转。我们可以用:
request.AllowAutoRedirect = false;设置重定向禁用,你就可以从headers的Location属性中获取重定向地址

posted on 2014-04-26 00:35  13m0n  阅读(233)  评论(0编辑  收藏  举报