C#获取网页的HTML码、下载网站图片、获取IP地址

1、根据URL请求获取页面HTML代码

/// <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;
}

2、下载网站图片

/// <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;
}

3、获取本地IP地址

   /// <summary>
/// 获取本地IP地址信息
/// </summary>
public string GetAddressIP()
{
///获取本地的IP地址
string AddressIP = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = _IPAddress.ToString();
}
}
return AddressIP.ToString();
}
上一篇:JUC Java多线程开发利器


下一篇:JUC并发编程二:Lock锁(重点)