1.简单发送Get请求
/// <summary>
/// 指定Url地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求链接地址</param>
/// <returns></returns>
public static string Get(string url)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
try
{
//获取内容
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
}
finally
{
stream.Close();
}
return result;
}
2.带请求参数的Get方法
/// <summary>
/// 发送Get请求
/// </summary>
/// <param name="url">地址</param>
/// <param name="dic">请求参数定义</param>
/// <returns></returns>
public static string Get(string url, Dictionary<string, string> dic)
{
string result = "";
StringBuilder builder = new StringBuilder();
builder.Append(url);
if (dic.Count > 0)
{
builder.Append("?");
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
}
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(builder.ToString());
//添加参数
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
try
{
//获取内容
using (StreamReader reader = new StreamReader(stream))
{
result = reader.ReadToEnd();
}
}
finally
{
stream.Close();
}
return result;
}
3.自定义指定Http请求头,自定义指定编码解析返回结果
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.Headers["Accept-Language"] = "zh-CN,zh;q=0.8";
req.Referer = "https://www.baidu.com/";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
string result = "";
//注意,此处使用的编码是:gb2312
//using (StreamReader reader = new StreamReader(stream, Encoding.Default))
using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gb2312")))
{
result = reader.ReadToEnd();
}