HttpWebRequest和C#中的表单身份验证

我是一个系统人员,目前正在做兼职Web开发项目,所以我很陌生.我正在尝试为www.portapower.com编写一个http客户端.

对于在网站上发布的某些项目,如果它们符合特定要求,它将打印一条消息.

在尝试访问此页面时:

http://www.portapower.com/getbainfo.php?fclasscode=1&code=CB1831B.40H&fbrand=QUNFUg==

该网站将我重定向注册页面

http://www.portapower.com/defaregit.php

这是我编码的片段:

CookieContainer myContainer = new CookieContainer();

HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://www.portapower.com/" + urlpart);
request.Credentials = new NetworkCredential("****","******");
request.CookieContainer = myContainer;
request.PreAuthenticate = true;
request.Method = "POST";
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();

Console.WriteLine(response.StatusCode);
Stream resstream = response.GetResponseStream();
Console.WriteLine(resstream.ToString());

我有用户名和密码,从浏览器使用时工作正常.请告诉我这是否是访问经过身份验证的页面的正确方法.

解决方法

这取决于网站如何验证用户.如果他们使用基本身份验证或Windows身份验证,那么您可以将 HttpWebRequest classCredentials property设置为用户名/密码/域信息,它应该可以工作.

但是,听起来您必须在网站上输入用户名/密码,这意味着您必须先登录该网站.查看主页面,这是我在< form>中找到的内容.处理登录的元素:

<form name="formLogin" method="post" action="./defalogin.PHP" >
  <input name="emtext" type="text" id="emtext" size="12">
  <input name="pstext" type="password" id="pstext" size="12">
  <input type="submit" name="Submit" value="Logn in" 
    onClick="return logincheck()" >
</form>

我只包括相关部分.

鉴于此,您必须首先使用HttpWebRequest转到./defalogin.PHP页面,然后发送emtext和pstext值.此外,请确保将CookieContainer property设置为CookieContainer的实例.当对POST的调用返回时,很可能会填充一个cookie,您必须将其发送回该站点.只需继续将CookieContainer属性设置在任何后续的HttpWebRequest实例上,以确保Cookie被传递到该CookieContainer.

然后,您将转到链接中指示的页面.

值得关注的还有logincheck javascript函数,但是看一下脚本源代码,它没有什么值得注意的.

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么