1

我有两个网址。如果我打开第一个 url,它将允许我们进行身份验证。第二个 URL 将 Web 内容作为 XML 数据打开。我需要读取该数据...但是当我执行第一个 URL 时,它的工作正常 Authentication 是 SUCCESS,但是我立即尝试打开第二个 URL,它说 Authentication failed 。如何维护从第一个 URL 到第二个 URL 的会话...

我的代码:

string url1 = "http://172.xx.xx.xx:xxxx/cms?login&username=santhu&password=welcom0e";
string url = "http://172.xx.xx.xx:xxxx//cms?status=ProcessStatus";
string result = null;
string result1 = null;
try
{
  WebClient client = new WebClient();
  result = client.DownloadString(url1);

  TextBox1.Text = result.ToString();
  result1 = client.DownloadString(url);
  TextBox2.Text = result1.ToString();
}
catch (Exception ex)
{           
}
4

2 回答 2

1
private class CookieAwareWebClient : WebClient
{
    public CookieAwareWebClient(): this(new CookieContainer())
    {
    }
    public CookieAwareWebClient(CookieContainer c)
    {
        this.CookieContainer = c;
    }
    public CookieContainer CookieContainer { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).CookieContainer = this.CookieContainer;
        }
        return request;
    }
}

Otherwise you can solve the problem by adding the values manually by using Firebug for cookies :)

webClient.Headers.Add("Cookie", "PHPSESSID=xxxxxxx; mosesuser=xxxxxxx; ");
于 2011-06-23T09:38:51.863 回答
0

您需要记住第一个请求中的“Set-Cookie”响应标头,并在您的第二个请求中发送它。

基本上,在第一个请求之后(可能在 DownloadString() 之后,您需要在 中找到标头client.ResponseHeaders,然后您需要以 client.Headers某种方式将其添加到。

编辑:似乎上面是不可能的,但你可以修改底层的 WebRequest 实例,看到这个问题:如何让 WebClient 使用 Cookies?

或者这个:http ://couldbedone.blogspot.com/2007/08/webclient-handling-cookies.html

于 2011-06-23T09:18:18.700 回答