C#获取网页的HTML码、下载网站图片 get post

时间:2023-12-09 16:00:07
/// <summary>
/// 获取网页的HTML码
/// </summary>
/// <param name="url">链接地址</param>
/// <param name="encoding">编码类型</param>
/// <returns></returns>
public static string GetHtmlStr(string url, string encoding)
{
string htmlStr = "";
if (!String.IsNullOrEmpty(url))
{
WebRequest request = WebRequest.Create(url); //实例化WebRequest对象
WebResponse response = request.GetResponse(); //创建WebResponse对象
Stream datastream = response.GetResponseStream(); //创建流对象
Encoding ec = Encoding.Default;
if (encoding == "UTF8")
{
ec = Encoding.UTF8;
}
else if (encoding == "Default")
{
ec = Encoding.Default;
}
StreamReader reader = new StreamReader(datastream, ec);
htmlStr = reader.ReadToEnd(); //读取数据
reader.Close();
datastream.Close();
response.Close();
}
return htmlStr;
}
/// <summary>
/// 下载网站图片
/// </summary>
/// <param name="picUrl"></param>
/// <returns></returns>
public string SaveAsWebImg(string picUrl)
{
string result = "";
string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/File/"; //目录
try
{
if (!String.IsNullOrEmpty(picUrl))
{
Random rd = new Random();
DateTime nowTime = DateTime.Now;
string fileName = nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(, ) + ".jpeg";
WebClient webClient = new WebClient();
webClient.DownloadFile(picUrl, path + fileName);
result = fileName;
}
}
catch { }
return result;
}