C# 登陆淘宝 (非webbrowser)

HttpWebRequest 代码:

/// <summary>
/// 通过POST方式发送数据
/// </summary>
/// <param name="Url">url</param>
/// <param name="postDataStr">Post数据</param>
/// <param name="cookie">Cookie容器</param>
/// <returns></returns>
publicstaticstringSendDataByPost(stringUrl,Encoding encoding,string postDataStr,refCookieContainer cookie,refstringAbsoluteUri)
{
string retString ="";
try
{
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(Url);
request.Timeout=40000;
if(cookie.Count==0)
{
request.CookieContainer=newCookieContainer();
cookie = request.CookieContainer;
}
else
{
request.CookieContainer= cookie;
}

request.Method="POST";
request.ContentType="application/x-www-form-urlencoded";
//request.ContentLength = postDataStr.Length;
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter =newStreamWriter(myRequestStream, encoding);
myStreamWriter.Write(postDataStr);
myStreamWriter.Close();

HttpWebResponse response =(HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader =newStreamReader(myResponseStream, encoding);
retString = myStreamReader.ReadToEnd();
AbsoluteUri= response.ResponseUri.AbsoluteUri;
myStreamReader.Close();
myResponseStream.Close();
}
catch(Exception ex)
{
thrownewException(ex.Message, ex);
}
return retString;
}

下面是登陆代码:

/// <summary>
/// 淘宝登陆
/// </summary>
/// <param name="Account"></param>
/// <param name="Password"></param>
/// <returns></returns>
privateboolLoginTaobao(stringAccount,stringPassword)
{
stringAbsoluteUri=string.Empty;
string result =WebHelper.SendDataByPost("http://login.taobao.com/member/login.jhtml",Encoding.GetEncoding("gb2312"),"TPL_username="+Utility.UrlEncode(Account)+
"&TPL_password="+Utility.UrlEncode(Password)+"&actionForStable=enable_post_user_action&action=Authenticator&event_submit_do_login=anything",ref cookieContainer,refAbsoluteUri);

if(Regex.IsMatch(result,"safe/check_ip.do"))
{
Platform.Common.StatusOutputEvent(newobject(),newPlatform.Common.StatusArgs(){Message="请在淘宝页面 [账号管理] 页面关闭 [登录保护] 功能或设置不进行二次验证地域."});
returnfalse;
}

if(result.IndexOf(aq_0)==-1&& result.IndexOf(aq_1)==-1)
{
returntrue;
}
else
{
Platform.Common.StatusOutputEvent(newobject(),newPlatform.Common.StatusArgs(){Message="["+this.Name+"] 登录失败."});
returnfalse;
}
}

cookieContainer  为  CookieContainer 类型,创建一个本类通用的对象,他将保存着你的登陆状态,登陆成功后进行其他任意操作只要提供 cookieContainer 对象即可。
 
Regex.IsMatch(result, "safe/check_ip.do") 为 true 的话,说明淘宝登陆设置中开启了 二次登陆验证,需要在淘宝设置中关闭才能登陆。
 
        private string aq_0 = "您需要安装安全控件,才可使用安全登录。";
        private string aq_1 = "您还未安装密码安全控件,安装后即可输入密码。";
 
if (result.IndexOf(aq_0) == -1 && result.IndexOf(aq_1) == -1)
 
返回的 HTML 代码中包含 以上两句话说明登陆失败,一般情况下需要淘宝用户手动登陆一下淘宝,然后再使用以上代码自动登陆就可以正常登陆了。
 
不要每次操作都登陆一下,要缓存好 cookies ,一段时间内登录次数太多淘宝会要求输入验证码,淘宝登陆验证码自动识别难度太大。
posted @ 2013-05-02 15:35  赤狐(zcm123)  阅读(1318)  评论(0编辑  收藏  举报