C#模拟http 发送post或get请求
/// <summary> /// 模拟HTTP提交表单并获取返回数据 /// POST /// </summary> /// <param name="Url">提交地址</param> /// <param name="postDataStr">参数</param> /// <param name="cookies">cookies</param> /// <returns></returns> public string HttpPost(string Url, string postDataStr, CookieCollection cookies) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr); request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36"; if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } using (StreamWriter myStreamWriter = new StreamWriter(request.GetRequestStream(), Encoding.GetEncoding("utf-8"))) { myStreamWriter.Write(postDataStr); myStreamWriter.Flush(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); response.Close(); return retString; } /// <summary> /// 模拟HTTP提交表单并获取返回数据 /// GET /// </summary> /// <param name="Url">提交地址</param> /// <param name="postDataStr">参数</param> /// <returns></returns> public string HttpGet(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
在post的时候有时也用的到cookie,像登录163发邮件时候就需要发送cookie,所以在外部一个cookie属性随时保存 CookieContainer cookie = new CookieContainer();
*注意:有时候请求会重定向,但我们就需要从重定向url获取东西,像QQ登录成功后获取sid,但上面的会自动根据重定向地址跳转。我们可以用:
request.AllowAutoRedirect = false;设置重定向禁用,你就可以从headers的Location属性中获取重定向地址。