C#模拟http 发送POST或GET请求
2017-03-01 10:44
465 查看
1、POST:
private 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);
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
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;
}
2、GET:
public string HttpGet(string Url, string postDataStr)
{
HttpWebResponse response = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (string.IsNullOrEmpty(postDataStr) ? "" : "?")
+ postDataStr);
request.Timeout = 30000; // 设置超时时间,单位毫秒。默认100000毫秒,100秒
try
{
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myStreamReader.Dispose();
myResponseStream.Close();
myResponseStream.Dispose();
return retString ;
} catch(Exception ex){
Console.WriteLine(ex.ToString());
} finally{
if (response != null)
{
response.Close();
}
}
return "false";
}
相关文章推荐
- C#模拟http 发送post或get请求的简单实例
- C#模拟http 发送post或get请求
- C#模拟http 发送post或get请求
- C#模拟发送http get、post请求的方式
- C#模拟http 发送post或get请求
- C#模拟http 发送POST或GET请求
- C#代码模拟http发送get和post请求
- C#模拟http 发送post或get请求
- C#模拟http 发送post或get请求
- C#模拟http 发送post或get请求
- Java后台模拟发送http的get和post请求,并测试
- C#模拟http 发送post请求 模拟登录
- 【实战】(二)android模拟qq登录(apache的httpClient发送get和post请求)
- curl模拟http发送get或post请求
- GET、POST请求处理中文问题(用HttpURLConnection模拟发送请求)
- BIM360: C#如何发送HTTP GET和POST请求登陆BIM 360 Glue以及获取项目列表
- 使用java程序模拟页面发送http的post请求
- 在C#用HttpWebRequest中发送GET/HTTP/HTTPS请求
- C# : WebRequest发起Http Post请求模拟登陆并cookie处理示例
- 在C#用HttpWebRequest中发送GET/HTTP/HTTPS请求