C#模拟模拟http 发送发送post或或get请求的简单实例请求的简单实例
private string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
request.CookieContainer = cookie;
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Cookies = cookie.GetCookies(response.ResponseUri);
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
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属性中获取重定向地址
以上这篇C#模拟http 发送post或get请求的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家
多多支持软件开发网。
您可能感兴趣的文章您可能感兴趣的文章:c# 在WebBrowser中用SendMessage模拟鼠标点击C#模拟Http与Https请求框架类实例C#采用
mouse_event函数实现模拟鼠标功能C#实现的三种模拟自动登录和提交POST信息的方法C# SendInput 模拟鼠标操作的实现
方法使用C#发送Http请求实现模拟登陆实例C#基于socket模拟http请求的方法c#模拟银行atm机示例分享C#模拟window操作
鼠标的方法C#如何使用Bogus创建模拟数据示例代码
评论0