基本的實現功能前面已經全部講完,基本上可以複製黏貼完成登錄百度的過程了
今天的這一貼就說說怎麼獲取百度的驗證碼
內容回顧:還記得前面第一貼說的如果登錄發生異常,百度會發回2個值嗎?是的,就是codeType和codeString這兩個值,用前面的JSON數據解析可以分別獲取。
前面也說到codeType是不變的(至少同一次請求時不變)。請求驗證碼的時候會要求傳遞這個參數,所以要想得到正確的驗證碼,這個參數是必不可少的,否則你請求多少次都是一個錯誤的驗證碼!
具體代碼入下:
//封裝更換驗證碼
public void ReGetCode()
{
string reSet_code = string.Format("https://passport.baidu.com/v2/?reggetcodestr&token={0}&tpl=zongheng&apiver=v3&tt={1}&fr=login&vcodetype={2}&callback=bd__cbs__ta1xss", token, Utility.GetTimeStamp(),vcodeType);
string codeContent = helper.GetPageResponse_Get(reSet_code, Utility.UrlDecode("http://passport.zongheng.com/?location=http%3A%2F%2Fwww.zongheng.com%2F"),"*/*");
if (_regex.IsMatch(codeContent))
codeContent = _regex.Match(codeContent).Value;
var codeResult = JsonConvert.DeserializeObject<Reget_Code>(codeContent);
_codestring = codeResult.Data_Code.VerifyStr;
string url_NewCode = string.Format("https://passport.baidu.com/cgi-bin/genimage?{0}", _codestring);
Bitmap bp= helper.GetCode(url_NewCode, Utility.UrlDecode("http://passport.zongheng.com/?location=http%3A%2F%2Fwww.zongheng.com%2F"));
pictureBox1.Image = bp;
}
可能這樣單獨看,有人會看不懂什麼意思,這裏就註釋一下
reSet_code 是代表獲取codestring的網頁,後面的參數分別是前面獲取到的token、生成的時間戳、以及codeType
codeContent 代表請求網頁後返回的內容,參數就是用到前面的HTTPHelper類的Post方法需要提供的參數
接下來是分析內容,獲取codestring,然後對驗證碼的圖片網頁重新發起請求,將驗證碼顯示回picturebox上
至於codeType怎麼來的,這個在請求登錄的時候,發生異常就會返回
下面是檢驗驗證碼是否正確的方法,在文本框輸入了驗證碼之後按回車
private void txtcode_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Thread th_2 = null;
if (e.KeyCode == Keys.Enter)
{
th_2 = new Thread(() =>
{
verifycode = txtcode.Text;
//先訪問一次驗證碼校驗頁面,看看驗證碼是否正確
string url_checkCode = string.Format("https://passport.baidu.com/v2/?checkvcode&token={0}&tpl=zongheng&apiver=v3&tt={1}&verifycode={2}&codestring={3}&callback=bd__cbs__nm74kc", token, Utility.GetTimeStamp(), verifycode, _codestring);
string checkcode = helper.GetPageResponse_Get(url_checkCode, Utility.UrlDecode("http://passport.zongheng.com/?location=http%3A%2F%2Fwww.zongheng.com%2F"), "*/*");
if (_regex.IsMatch(checkcode))
checkcode = _regex.Match(checkcode).Value;
var code_msg = JsonConvert.DeserializeObject<CheckvCode>(checkcode);
CodeMsg(code_msg.ErrInfo.No);
if (code_msg.ErrInfo.No != "0")
return;
LoginStatus status = Login(verifycode, _codestring, token, raskey, userIndex);
GoComment_Page(status);
th_2.Abort();
});
th_2.Start();
th_2.IsBackground = true;
}
}
好了,今天就到這裏,如果有問題,歡迎評論交流~