string url = "网页图片的src";
AppLog.Info("取照片路径:" + url);
Uri uri = new Uri(url);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
string sCookie = "";
sCookie = GetCookieString(webMain.Url.ToString());
string[] cookies = sCookie.Split(';');
foreach (var item in cookies)
{
if (item.Contains("SSIONID"))
{
sCookie = item;
}
}
string[] cookieID = sCookie.Split('=');
AppLog.Debug("获取到的cookie:"+cookieID[1]) ;
CookieContainer cookies1 = new CookieContainer();
System.Net.Cookie cookie = new System.Net.Cookie("SHRIOSESSIONID", cookieID[1], "/", uri.Host);
cookies1.Add(cookie);
cookies1.Add(new System.Net.Cookie("Age", "2039", "/", uri.Host));
request.CookieContainer = cookies1;
//string cookies = webMain.Document.Cookie;
// request.Headers.Add(HttpRequestHeader.Cookie, cookies);
request.KeepAlive = false;
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
if (res.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = res.GetResponseStream())
{
MemoryStream ms = Stream2MemoryStream(stream);
ms.Seek(0, SeekOrigin.Begin);
byte[] outbytes = new byte[(int)ms.Length];
ms.Read(outbytes, 0, outbytes.Length);
ms.Flush();
ms.Close();
FileStream fs = new FileStream(ComBizz.idInfos.SOnePath, FileMode.Create);
AppLog.Debug("照片保存路径:" + ComBizz.idInfos.SOnePath);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(outbytes);
bw.Close();
fs.Close();
}
}
else { AppLog.Info("照片链接未响应" + url); }
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref int pcchCookieData, int dwFlags, object lpReserved);
//取出Cookie,当登录后才能取
private static string GetCookieString(string url)
{
// Determine the size of the cookie
int datasize = 256;
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
{
if (datasize < 0)
return null;
// Allocate stringbuilder large enough to hold the cookie
cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
return null;
}
return cookieData.ToString();
}
private MemoryStream Stream2MemoryStream(Stream stream)
{
MemoryStream ms = new MemoryStream();
byte[] bytes = new byte[1024];
int byteread;
while ((byteread = stream.Read(bytes, 0, bytes.Length)) > 0)
{
ms.Write(bytes, 0, byteread);
}
return ms;
}