核心代码(获取HTML):
#region 根据URL地址获取信息GET
public static String GetResult(string url)
{
return GetResult(url, Encoding.Default);
}
#endregion
#region 根据URL地址获取对应编码信息
public static String GetResult(string url, Encoding encoding)
{
try
{ var webRequest = (HttpWebRequest)WebRequest.Create(url);
//获取响应结果
var webResponse = (HttpWebResponse)webRequest.GetResponse();
//获取响应流
Stream stream = webResponse.GetResponseStream();
using (StreamReader streamReader = new StreamReader(stream, encoding))
{
string result = String.Empty;
result = streamReader.ReadToEnd();
streamReader.Close();
webResponse.Close();
webRequest.Abort();
return result;
}
}
catch (Exception ex)
{
return "-1";
//return ex.Message.Length > 100 ? ex.Message.Substring(0, 100) : ex.Message;
}
}
#endregion

方法调用:

string strUrl = @"http://192.168.0.155:8181/";  //获取HTML的地址
string strTemp = GetResult(strUrl, System.Text.Encoding.GetEncoding("utf-8"));

if (!strTemp.Equals("-1"))
{
strTemp = strTemp.Substring(strTemp.IndexOf("<!--begin-->"));
strTemp = strTemp.Substring(0, strTemp.IndexOf("<!--end-->"));
}
return strTemp;

核心代码(下载图片):

 public static void getimages(string url)
{
//创建一个request 同时可以配置requst其余属性
System.Net.WebRequest imgRequst = System.Net.WebRequest.Create(url);
//在这里我是以流的方式保存图片
System.Drawing.Image downImage = System.Drawing.Image.FromStream(imgRequst.GetResponse().GetResponseStream());
string dertory = string.Format(@"D:\imgfg.cn\5r\{0}\", DateTime.Now.ToString("yyyy-MM-dd"));
string fileName = string.Format("{0}.jpg", DateTime.Now.ToString("HHmmssffff"));
if (!System.IO.Directory.Exists(dertory))
{
System.IO.Directory.CreateDirectory(dertory);
}
downImage.Save(dertory + fileName);
downImage.Dispose();
//用完一定要释放
}

方法调用:

string strUrl = @"https://www.baidu.com/img/bd_logo1.png?qua=high&where=super";  //网络图片或者本地图片地址

getimages(strUrl);

05-02 10:55