获取网站的cookie

bychgh 2010-11-26 02:51:54
模拟用户输入,来获得一个cookie,
我想获得 这个网站的 http://www.boyuanrc.com/job/grqz.asp

写的代码如下



public CookieContainer Get_Login()
{
CookieContainer cc = new CookieContainer();
string FormURL = "http://www.boyuanrc.com/job/login.asp"; //处理表单的绝对URL地址
string FormData = "name=cf123&pwd=123456&image2.x=13&image2.y=22&user=1"; //表单需要提交的参数
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(FormData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FormURL);
request.Method = "POST"; //数据提交方式
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
//模拟一个UserAgent
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);

newStream.Close();

request.CookieContainer = cc;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cc.Add(response.Cookies);
Stream stream = response.GetResponseStream();
string WebContent = new StreamReader(stream, System.Text.Encoding.Default).ReadToEnd();
response.Close();
return cc;
}




结果报错了,获取另外一个网站是正常的,不知道这个网站怎么不行,麻烦告诉看看,应该怎么改写
...全文
657 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
bychgh 2010-12-03
  • 打赏
  • 举报
回复
http://www.cnblogs.com/cresuccess/archive/2009/12/09/1619977.html

我们编码实现请求一个页面时,请求的代码类似如下代码:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl);req.UserAgent = "MSIE6.0";req.Method = "GET";HttpWebResponse res = (HttpWebResponse)req.GetResponse();StreamReader sr = new StreamReader(res.GetResponseStream(), strEncode);strHtml = sr.ReadToEnd();sr.Close();res.Close(); 但是,如果我们请求的这个页面正好是一个有异常发生的页面,或者不存在的页面。我们上面的代码就会在

req.GetResponse();这里抛出异常:远程服务器返回错误: (500) 内部服务器错误。
我们通过上面的代码,是不能得到错误发生时候的页面源代码的。



分析原因:

(HttpWebResponse)req.GetResponse(); 这行代码中做了如下一件事情:

当服务器段ASP.net程序有 Exception 发生时,客户端应用程序接受了HTTP 协议错误后。把这个HTTP 协议错误转换成 Status 设置为 WebExceptionStatus.ProtocolError 的 WebException,并且把这个异常throw出来。



解决问题

那如果我们想获得错误发生时候服务器段错误页面的源代码该如何做呢?

其实非常非常简单的做法,我们用下面的代码就不论错误发生与否,都可以获得服务器段页面的源代码。

HttpWebResponse res; try { res = (HttpWebResponse)req.GetResponse(); } catch (WebException ex) { res = (HttpWebResponse)ex.Response; } StreamReader sr = new StreamReader(res.GetResponseStream(), strEncode); strHtml = sr.ReadToEnd();当异常发生事后,WebException 中不仅有 StatusCode 标志着 HTTP 的错误代码,而且它的 Response 属性还包含由服务器发送的 WebResponse,来指示遇到的实际 HTTP 错误。
龍月 2010-11-29
  • 打赏
  • 举报
回复

.Net/C# 应用程序直接读取本地 Cookies 文件(WinXP SP2 调用 API: InternetGetCookie 无果)
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Win32;
public class Class1
{
static void Main(string[] args)
{
System.Console.WriteLine(GetCookiesFromFiles("et8")); //支持 WinXP SP2
System.Console.WriteLine(GetCookie("http://bbs.et8.net"));
}

[System.Runtime.InteropServices.DllImport("wininet.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto, SetLastError=true)]
public static extern bool InternetGetCookie(string lpszUrlName,string lpszCookieName,StringBuilder lpszCookieData,ref int lpdwSize);

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
internal static extern Int32 GetLastError();

public static string GetCookie(string url) //Win32 API
{
int size = 1000;
StringBuilder sb = new StringBuilder(size);

if (!InternetGetCookie(url,"", sb,ref size))
{
Console.WriteLine("Error code:{0}", GetLastError());
}
return sb.ToString();
}

public static string GetCookiesFromFiles(string MasterDomain) //Cookies File
{
string S = null;
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", false);
if (key != null)
{
string val = (string) key.GetValue("Cookies");
if (val!= null)
{
string[] F = Directory.GetFiles(val);
string s = null;
int i;
Regex r = new Regex(@".*@" + MasterDomain + @"*\[\d+\].txt");
for (i = 0; i < F.Length; i++)
{
if (r.IsMatch(F[i]))
{
s = F[i];
}
}
if (s != null) //s 就是最新文件
{
StreamReader sr = new StreamReader(s);
s = null;
i = 1;
while ((s = sr.ReadLine())!= null)
{
if (s == "*" || s == "\n")
{
i = 0;
}
//每节只读两行
if (i == 1)
{
S += s;
}
else if (i == 2)
{
S += "=" + s + "; ";
}
i++;
}
}
}
}
return S;
}
}



龍月 2010-11-29
  • 打赏
  • 举报
回复


/**/
/// <summary>
/// 通过COM来获取Cookie数据。
/// </summary>
/// <param name="url">当前网址。</param>
/// <param name="cookieName">CookieName.</param>
/// <param name="cookieData">用于保存Cookie Data的<see cref="StringBuilder"/>实例。</param>
/// <param name="size">Cookie大小。</param>
/// <returns>如果成功则返回<c>true</c>,否则返回<c>false</c>。</returns>
[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetGetCookie(
string url, string cookieName,
StringBuilder cookieData, ref int size);
/**/
/// <summary>
/// 获取当前<see cref="Uri"/>的<see cref="CookieContainer"/>实例。
/// </summary>
/// <param name="uri">当前<see cref="Uri"/>地址。</param>
/// <returns>当前<see cref="Uri"/>的<see cref="CookieContainer"/>实例。</returns>
public static CookieContainer GetUriCookieContainer(Uri uri,Uri uri2)
{
CookieContainer cookies = null;

// 定义Cookie数据的大小。
int datasize = 256;
StringBuilder cookieData = new StringBuilder(datasize);

if (!InternetGetCookie(uri.ToString(), null, cookieData,
ref datasize))
{
if (datasize < 0)
return null;

// 确信有足够大的空间来容纳Cookie数据。
cookieData = new StringBuilder(datasize);


if (!InternetGetCookie(uri.ToString(), null, cookieData, ref datasize))
return null;
}


if (cookieData.Length > 0)
{
cookies = new CookieContainer();
// cookies.SetCookies(uri, cookieData.ToString().Replace(";", ","));

// CookieCollection temp = cookies.GetCookies(uri);

string[] cookstr = cookieData.ToString().Split(';');

int i = 0;
foreach (string str in cookstr)
{
try
{
// string[] cookieNameValue = str.Split( '=');
Cookie ck = new Cookie();
int index = str.Trim().IndexOf('=');
ck.Name = str.Trim().Substring(0, index).Trim();
ck.Value = str.Trim().Substring(index+1).Trim();
// ck.Domain = uri.ToString();//必须写对
cookies.Add(uri2, ck);

i++;
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
}

// MessageBox.Show(i.ToString());

CookieCollection temp = cookies.GetCookies(uri2);

}
return cookies;
}

ycproc 2010-11-26
  • 打赏
  • 举报
回复
帮顶
一克代码 2010-11-26
  • 打赏
  • 举报
回复
是cookie
一克代码 2010-11-26
  • 打赏
  • 举报
回复
它网站是不是用cooike啊?

62,052

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

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