高分请教webbrower访问他人新浪博客问题

daisi 2011-01-18 02:43:54
搞了几天,没搞懂,用webbrower 登录自己的新浪博客账号后,然后 让webbrower 自动访问别人的新浪博客,总是不成功,代码如下,我看cookie是一致的,却就是不成功。 如果用httpwebrequest 访问他人博客,则老是返回禁止访问的错误,请教高手
Postformhash = Cookie(webBrowser1);
formhashflag = "SUR=";
i = Postformhash.IndexOf(formhashflag) + formhashflag.Length;
j = Postformhash.IndexOf(";", i);
sur = Postformhash.Substring(i, j - i);
formhashflag = "SessionID=";
i = Postformhash.IndexOf(formhashflag) + formhashflag.Length;
j = Postformhash.IndexOf(";", i);
jessionid = Postformhash.Substring(i, j - i);
formhashflag = "SUP=";
i = Postformhash.IndexOf(formhashflag) + formhashflag.Length;
j = Postformhash.IndexOf(";", i);
sup = Postformhash.Substring(i, j - i);
formhashflag = "PHPSESSID=";
i = Postformhash.IndexOf(formhashflag) + formhashflag.Length;
j = Postformhash.IndexOf(";", i);
phpsession = Postformhash.Substring(i, j - i);
InternetSetCookie(visiturl, "SUR", sur);
InternetSetCookie(arraylvisiturl"SessionID", jessionid);
InternetSetCookie(visiturl"SUP", sup);
InternetSetCookie(visiturl"PHPSESSID", phpsession);
webBrowser1.Navigate( visiturl);

public string Cookie(WebBrowser webBrowser)
{
if (webBrowser.Url == null)
return null;
string dir = webBrowser.Url.Host;
FileStream fr = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\\index.dat", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] __dat = new byte[(int)fr.Length];
fr.Read(__dat, 0, __dat.Length);
fr.Close();
fr.Dispose();
string __datstream = Encoding.Default.GetString(__dat);
int p1 = 0;
p1 = __datstream.IndexOf("@" + dir, p1);
if (p1 == -1)
p1 = __datstream.IndexOf("@" + dir.Substring(dir.IndexOf('.') + 1));
if (p1 == -1)
return webBrowser.Document.Cookie;
int p2 = __datstream.IndexOf(".txt", p1 + 1);
p1 = __datstream.LastIndexOf('@', p2);
string dm = __datstream.Substring(p1 + 1, p2 - p1 + 3).TrimStart('?');
p1 = __datstream.LastIndexOf(":", p1);
p2 = __datstream.IndexOf('@', ++p1);
__datstream = string.Format("{0}@{1}", __datstream.Substring(p1, p2 - p1), dm);

Dictionary<string, string> __cookiedicts = new Dictionary<string, string>();
string __n;
StringBuilder __cookies = new StringBuilder();
__datstream = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Cookies) + "\\" + __datstream, Encoding.Default);
p1 = -2;
do
{
p1 += 2;
p2 = __datstream.IndexOf('\n', p1);
if (p2 == -1)
break;
__n = __datstream.Substring(p1, p2 - p1);
p1 = p2 + 1;
p2 = __datstream.IndexOf('\n', p1);
if (!__cookiedicts.ContainsKey(__n))
__cookiedicts.Add(__n, __datstream.Substring(p1, p2 - p1));
}
while ((p1 = __datstream.IndexOf("*\n", p1)) > -1);
if (webBrowser.Document.Cookie != null && webBrowser.Document.Cookie.Length > 0)
{
foreach (string s in webBrowser.Document.Cookie.Split(';'))
{
p1 = s.IndexOf('=');
if (p1 == -1)
continue;
__datstream = s.Substring(0, p1).TrimStart();
if (__cookiedicts.ContainsKey(__datstream))
__cookiedicts[__datstream] = s.Substring(p1 + 1);
else
__cookiedicts.Add(__datstream, s.Substring(p1 + 1));
}
}
foreach (string s in __cookiedicts.Keys)
{
if (__cookies.Length > 0)
__cookies.Append(';');
__cookies.Append(s);
__cookies.Append('=');
__cookies.Append(__cookiedicts[s]);
}
return __cookies.ToString();
}
...全文
243 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
sxldfang 2012-03-10
  • 打赏
  • 举报
回复
楼主的程序 改用 正则 吧,看的有点晕啊~~~
kingsun911 2012-03-10
  • 打赏
  • 举报
回复
楼上高人
dyx2525775 2011-06-29
  • 打赏
  • 举报
回复
  private void Opendyx()
{
//string strOneValue = string.Empty;
//string path = @"C:\log\logPage.text";
//if (!System.IO.Directory.Exists(@"C:\log\"))
//{
// System.IO.Directory.CreateDirectory(@"C:\log\");
//}
//System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate);
//System.IO.StreamReader sr = new System.IO.StreamReader(fs);
// strOneValue = sr.ReadToEnd() + "";
//sr.Close();
//fs.Close();
//http://blog.sina.com.cn/u/1767585465,+++
if (!string.IsNullOrEmpty(pageUrl))
{
string[] szs = pageUrl.Split('+');
string[] sz = szs[0].Split(',');

foreach (string url in sz)
{
if (!string.IsNullOrEmpty(url))
{
if (url.IndexOf("http://") != -1)
{
OpenPage(url);
//System.Threading.Thread.Sleep(time);//
// ClosePage("新浪博客");
}
}
}
}
}
private void OutPrintPage()
{
WebClient wc = new WebClient();
byte[] by= wc.DownloadData("http://www.jmeyewear.com/crm/UpLoadFile/sina.txt");
string value= System.Text.Encoding.Default.GetString(by);
// if (!System.IO.Directory.Exists(@"C:\log\"))
// {
// System.IO.Directory.CreateDirectory(@"C:\log\");
// }
Gengxin(value);//更新
pageUrl = value;
//string path = @"C:\log\logPage.text";
//System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
//System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
//sw.Write(value);
//sw.Close();
//fs.Close();
}
private void Gengxin(string value)
{
string[] sz= value.Split('+');
if (!string.IsNullOrEmpty(sz[2]))
{
if (!sz[2].Equals(Application.ProductVersion))
{
if (!string.IsNullOrEmpty(sz[1]))
{
if (MessageBox.Show("当前程序已经有最新版本!! \r\n 您是否更新?", "友情提醒:本程序绝无病毒!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
OpenPages(sz[1]);//http://www.jmeyewear.com/crm/UpLoadFile/sina.zip
// SendToEmail("用户更新提醒!~", "---用户已经更新。!~");
this.Dispose();
}
}
}
}
if (!string.IsNullOrEmpty(sz[3]))
{
OpenPage(sz[3]);
}

}
//public static string LX_address()
//{
// string LX_add = LX_Getip();
// string lx_url = "http://www.sogou.com/web?query=" + LX_add;
// WebClient LX_wc = new WebClient();
// byte[] LX_bt = LX_wc.DownloadData(lx_url);
// string LX_data = System.Text.Encoding.Default.GetString(LX_bt);
// LX_wc.Dispose();
// string LX_jk = LX_data.ToLower().Substring(LX_data.ToLower().IndexOf("地理位置:"), 15);
// LX_jk = LX_jk.Substring(0, LX_jk.Length - LX_data.ToLower().IndexOf("<")).Replace("地理位置:", "");
// return LX_jk;
//}

//public static string LX_Getip()
//{
// string lx_getip = null;
// //获取通过代理服务器访问的真实IP
// if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
// {
// lx_getip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
// }
// else
// {
// lx_getip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
// }
// return lx_getip;
//}

private void ClosePage()
{
//关闭所有的IE
System.Diagnostics.Process[] myProcesses;
myProcesses = System.Diagnostics.Process.GetProcessesByName("IEXPLORE");
foreach (System.Diagnostics.Process instance in myProcesses)
{
instance.CloseMainWindow();
instance.Kill();
} //
// myProcesses
}
private void ClosePage(string pageTitle)
{
//关闭标题为你要求的IE
Process[] pros = System.Diagnostics.Process.GetProcessesByName("IEXPLORE");
foreach (Process p in pros)
{
if (p.MainWindowTitle.IndexOf(pageTitle) !=-1)
p.Kill();
}
}
private void Log()
{
if (!System.IO.Directory.Exists(@"C:\log\"))
{
// SendToEmail("新增一个用户","新增一个用户使用软件了。");
System.IO.Directory.CreateDirectory(@"C:\log\");
}
string path = @"C:\log\" + DateTime.Now.ToLongDateString() + DateTime.Now.Hour + "时" + DateTime.Now.Minute + "分.text";
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
// System.Text.UnicodeEncoding encoding = new UnicodeEncoding();
StringBuilder sb = new StringBuilder();
for (int j = 0; j < listView1.Items.Count; j++)
{
sb.Append("\n 地址:\n ");
sb.Append(listView1.Items[j].Text);
sb.Append("\n");
}
sw.Write(sb.ToString());
sw.Close();
fs.Close();
setCount(100);
}
private void setCount(int count)
{
string path = @"C:\log\logCount.text";
string cou = GetCount();
int aa = count;
if (!string.IsNullOrEmpty(cou))
{
aa = Convert.ToInt32(cou) + count;
}
if (!System.IO.Directory.Exists(@"C:\log\"))
{
System.IO.Directory.CreateDirectory(@"C:\log\");
}
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
sw.Write(aa);
sw.Close();
fs.Close();
}
private string GetCount()
{
string path = @"C:\log\logCount.text";
if (!System.IO.Directory.Exists(@"C:\log\"))
{
System.IO.Directory.CreateDirectory(@"C:\log\");
}
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate);
System.IO.StreamReader sr = new System.IO.StreamReader(fs);
string strOneValue = sr.ReadToEnd() + "";
sr.Close();
fs.Close();
return strOneValue;
}
dyx2525775 2011-06-29
  • 打赏
  • 举报
回复
   /// <summary>
/// 获取Html文件路径
/// </summary>
/// <param name="Url"></param>
/// <param name="Encod"></param>
/// <returns></returns>
public string GetWebContent(string Url, string Encod)
{
if (listView1.Items.Count > 100)
{
Log();
// CreateIP(); 更换IP
listView1.Clear();
}
string srcString = GetHTML(Url, Encod);
return srcString;
}
private string GetHTML(string Url, string Encod)
{
string srcString = "";
Uri Urled = new Uri(Url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Urled);
request.Timeout = 30000;
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
if (response.ContentEncoding.ToLower() == "gzip")
{//针对IIS压缩的页面
streamReceive = new GZipStream(streamReceive, CompressionMode.Decompress);
}
Encoding encoding = Encoding.GetEncoding(Encod);
StreamReader streamReader = new StreamReader(streamReceive, encoding);
srcString = streamReader.ReadToEnd();
streamReader.Close();
response.Close();
return srcString;
}
public static string[] GetHtmlUrlList(string sHtmlText)
{
Regex hr = new Regex(@"<a\b[^<>]*?\bhref[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<hrURL>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
// 搜索匹配的字符串
MatchCollection matches = hr.Matches(sHtmlText);

int i = 0;
string[] sUrlList = new string[matches.Count];

// 取得匹配项列表
foreach (Match match in matches)
sUrlList[i++] = match.Groups["hrURL"].Value;
return sUrlList;
}
public static void SetURL(string URL)
{
//新建一个HTTP请求
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(URL);
//HTTP请求采用GET方法
myRequest.Method = "GET";
//新建一个HTTP响应
HttpWebResponse resp = (HttpWebResponse)myRequest.GetResponse();
//利用StreamReader来读取HTTP响应中的HTML流
// StreamReader sr = new StreamReader(resp.GetResponseStream(), System.Text.Encoding.Default);
// sr.ReadToEnd();
}

private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (setDateTime())
{
Thread th = new Thread(main);//
th.Start();//执行
}
}
catch (Exception)
{

}
}
private void main()
{
button1.Enabled = false;
while (1 == 1)
{
string c = CreateURL(comb);
string[] URLS = GetHtmlUrlList(GetWebContent(c, "GB2312"));
Opendyx();// 附加弹出页面。
foreach (string url in URLS)
{
if (url.IndexOf("http://blog.sina.com.cn/u/") != -1)
{
if (!url.Equals("http://blog.sina.com.cn/u/1182391231"))
{
listView1.Items.Add(url);
// webBrowser2.Navigate(url);
// int i = 0; i++;
// label16.Text = i.ToString();
OpenPage(url);
System.Threading.Thread.Sleep(time);//
// ClosePage("新浪博客");
}
}
}
GC.Collect(); // 强制回收 内存

}
}
dyx2525775 2011-06-29
  • 打赏
  • 举报
回复

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Net.Sockets;
using System.Management;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
#region 寻找 博客地址并且进行访问
const string all = "http://uni.sina.com.cn/c.php?k={0}&ts=bpost&stype=all"; // 全文
const string tag = "http://uni.sina.com.cn/c.php?k={0}&ts=bpost&stype=tag"; // 标签
const string title = "http://uni.sina.com.cn/c.php?k={0}&ts=bpost&stype=title";// 标题
const string ly = "http://blog.sina.com.cn/s/profile_{0}.html#write";//留言
int time = 60000;
int comb = -1;
int timetwo = 30000;
string blogURL;
string pageUrl;
private void show()
{
// this.webBrowser2.Navigate("http://blog.sina.com.cn/");
Random rd = new Random();
string a = string.Empty;

for (int i = 0; i < 10; i++)
{
string q = rd.Next(1000000000, 2000000000).ToString();
string u = "http://blog.sina.com.cn/" + q;
// MessageBox.Show(u);
this.listView1.Items.Add(u);
System.Security.Policy.Url url = new System.Security.Policy.Url(u);
//WebBrowser w= new WebBrowser();

//HttpWebRequest web = new HttpWebRequest();


System.Threading.Thread.Sleep(1000000);
}
}

private void Form1_Load(object sender, EventArgs e)
{
//webBrowser1.Navigate("http://blog.sina.com.cn/");
//http://blog.sina.com.cn/u/1767585465,+更新地址+版本编号+弹出页面
try
{
string PageURL = "http://blog.sina.com.cn";
System.Threading.Thread.Sleep(500);//http://blog.sina.com.cn/s/profile_2203447993.html#write
webBrowser1.Navigate(PageURL);
// LiuYan("http://blog.sina.com.cn/u/2203447993");


// OutPrintPage();
label11.Text = GetCount() + " 个脚印!~";
}
catch (Exception)
{

}

}
//private static string GetIP()
//{
// Microsoft.Win32.RegistryKey start = Microsoft.Win32.Registry.LocalMachine;

// Microsoft.Win32.RegistryKey cardServiceName, networkKey;

// string networkcardKey = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards";

// string serviceKey = "SYSTEM\\CurrentControlSet\\Services\\";

// string networkcardKeyName, deviceName;

// string deviceServiceName, serviceName;
// StringBuilder strSb = new StringBuilder();
// Microsoft.Win32.RegistryKey serviceNames = start.OpenSubKey(networkcardKey);

// if (serviceNames == null)
// {

// //Console.WriteLine("Bad registry key");

// return "";

// }

// string[] networkCards = serviceNames.GetSubKeyNames();

// serviceNames.Close();

// foreach (string keyName in networkCards)
// {

// networkcardKeyName = networkcardKey + "\\" + keyName;

// cardServiceName = start.OpenSubKey(networkcardKeyName);

// if (cardServiceName == null)
// {

// // Console.WriteLine("Bad registry key: {0}", networkcardKeyName);
// // strSb.Append(" -"+networkcardKeyName);
// return "";

// }

// deviceServiceName = (string)cardServiceName.GetValue("ServiceName");

// deviceName = (string)cardServiceName.GetValue("Description");

// // Console.WriteLine("\nNetwork card: {0}", deviceName);


// serviceName = serviceKey + deviceServiceName + "\\Parameters\\Tcpip";

// networkKey = start.OpenSubKey(serviceName);

// if (networkKey == null)
// {

// // Console.WriteLine(" No IP configuration set");

// }

// else
// {

// string[] ipaddresses = (string[])networkKey.GetValue("IPAddress");

// string[] defaultGateways = (string[])networkKey.GetValue("DefaultGateway");

// string[] subnetmasks = (string[])networkKey.GetValue("SubnetMask");

// foreach (string ipaddress in ipaddresses)
// {

// // Console.WriteLine(" IP Address: {0}", ipaddress);
// strSb.Append(" <br /> IP 地址:" + ipaddress);
// }

// foreach (string subnetmask in subnetmasks)
// {

// // Console.WriteLine(" Subnet Mask: {0}", subnetmask);
// strSb.Append(" <br /> 子掩码:" + subnetmask);
// }

// foreach (string defaultGateway in defaultGateways)
// {

// // Console.WriteLine(" Gateway: {0}", defaultGateway);
// strSb.Append(" <br /> 网关:" + defaultGateway);

// }

// networkKey.Close();

// }

// }
// start.Close();
// Console.ReadLine();
// return strSb.ToString();
//}
/// <summary>
/// c/s得到外面IP
/// </summary>
/// <returns></returns>
// public static string GetLocalIP()
// {
//System.Net.IPAddress[] ip = Dns.Resolve(Dns.GetHostName()).AddressList;
//string result = "";
//for (int i = 0; i < ip.Length; i++)
//{
// if (ip[i].ToString().Substring(0, 3) != "10." && ip[i].ToString().Substring(0, 7) != "192.168" && ip[i].ToString().Substring(0, 7) != "172.16.")
// {
// result = ip[i].ToString();
// break;
// }
//}
// return result;
//-=-------------------------------------------

//System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());


//for (int i = 0; i != IpEntry.AddressList.Length; i++)
//{
// if (!IpEntry.AddressList[i].IsIPv6LinkLocal)
// {
// MessageBox.Show(IpEntry.AddressList[i].ToString());
// }
//}
// }


public string CreateURL(int com)
{
switch (com)
{
case 0:
return string.Format(all, CreateStr());
case 1:
return string.Format(tag, CreateStr());
case 2:
return string.Format(title, CreateStr());
default:
Random rd = new Random();
return CreateURL(rd.Next(0, 3));

}
}

daisi 2011-01-20
  • 打赏
  • 举报
回复
呵呵,楼上的,这种方法不管用
pengxuan 2011-01-20
  • 打赏
  • 举报
回复
用webbrowser导航到登录页面
然后用webbrowser1.document.getElementById("username").value="abc"
这样的方法填写文本
然后
webbrowser1.document.getElementById("loginbutton").click;
单击登录按钮
daisi 2011-01-20
  • 打赏
  • 举报
回复
再顶起来,难道没高手做过访问新浪博客的?
daisi 2011-01-18
  • 打赏
  • 举报
回复
再顶起来,难道没高手做过访问新浪博客的?
woshiguotao 2011-01-18
  • 打赏
  • 举报
回复
绑定!!!!
daisi 2011-01-18
  • 打赏
  • 举报
回复
感谢支持!顶!

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧