日期:2014-05-17  浏览次数:20898 次

C#如何模拟登陆?
点击“登录”按钮会执行以下函数:

res= loginapi.login("109066557@qq.com", "123456");

login函数定义如下:

public bool login(string username, string password)
{
    public string baseUrl = @"http://api.website.com/";
    DataRequest request = new DataRequest();
    request.paramData = @"?username="+username+@"&password="+password;
    request.RequestURL(baseUrl + "login.php");
    int delay = 5;
    while (request.statusCode!= HttpStatusCode.OK)
    {
        Thread.Sleep(1000);
        delay--;
        if (delay <= 0)
        {
            MessageBox.Show("超时!");
            MessageBox.Show(request.statusCode.ToString());
            return false;
        }
    }
    MessageBox.Show(request.resData);
    return true;
}

DataRequest类定义如下:

public class DataRequest
{
    public string paramData=string.Empty;
    public string resData=string.Empty;
    public string resData = "测试";
    public HttpStatusCode statusCode;
    public Exception errorAsync;
    public static Encoding dataEncode = Encoding.UTF8;
    public void RequestURL(string url)
    {
        statusCode = HttpStatusCode.Created;
        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
        webReq.Method = "POST";
        webReq.ContentType = "application/x-www-form-urlencoded";
        webReq.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), webReq);
    }
    private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);
            byte[] byteArray = dataEncode.GetBytes(paramData);
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();
&nbs