基础类库积累--HTTP操作类
前言:
积累Http
HttpPost
public static string Post(string url, string data, Dictionary<string, string> headers)
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (headers != null)
{
foreach (var key in headers.Keys)
{
request.Headers.Add(key, headers[key]);
}
}
//写数据
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "application/json";
Stream reqstream = request.GetRequestStream();
reqstream.Write(bytes, 0, bytes.Length);
//读数据
request.Timeout = 300000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamReceive, Encoding.UTF8);
string strResult = streamReader.ReadToEnd();
//关闭流
reqstream.Close();
streamReader.Close();
streamReceive.Close();
request.Abort();
response.Close();
return strResult;
}
简介:
- url:请求地址
- data:发送的数据
- headers:头部信息
- ContentType:这个要注意,如果Post的时候报HTTP:403,请检查你传递的数据格式,以及传递的类型
HttpGet
public static String Get(String url, Encoding encode)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/html, application/xhtml+xml, */*";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream rs = response.GetResponseStream();
StreamReader sr = new StreamReader(rs, encode);
var result = sr.ReadToEnd();
sr.Close();
rs.Close();
return result;
}
简介:
- url:请求的地址
- encode:请求网页的编码【如果编码不一样,请求的结果可能是乱码】
- ContentType:不同的地址,他返回的类型不一样[如果是API的接口,一般是application/json,如果是网页,一般是text/html]
总结:
在C#后台开发过程中,我们经常会用到Http的Get和Post这两种方式,还有其他的方式什么Delete,Put自己了解,我用C#做爬虫的时候,有时候需要解析网页,使用HttpGet,获取网页信息进行处理,有时候需要模拟用户登陆【走协议】,使用HttpPost提交数据。