1

I am trying to log in to a website from my C# web application to send emails directly from the application instead of making user visit the website personally.

NOTE: The website, I am trying to log into changes the id of the textboxes everytime the page is loaded, EVEN DURING THE SAME SESSION. Therefore I decided to read the page source, extract the id of the textbox and then use that id while posting the message.

public partial class sender : System.Web.UI.Page
{
    string userID, userPwd, recepsID, msgText, loginResponseString, sessionCode, queryCode;
    private HttpWebRequest initRequest, loginRequest, msgRequest;
    private HttpWebResponse initResponse, loginResponse;
    private Object lockObj = new Object();

    protected void Page_Load(object sender, EventArgs e)
    {
        userID = Request.QueryString["userNumber"];
        userPwd = Request.QueryString["userPwd"];
        recepsID = Request.QueryString["receps"];
        msgText = Request.QueryString["msgBody"];
        if (userID != null && userPwd != null && recepsID != null & msgText != null)
            doLoginAndSendMessage(userID, userPwd, recepsID, msgText);
        else
            Response.Write("Some values are missing");
    }

    public void doLoginAndSendMessage(string uid, string pwd, string recepIds, string msg)
    {
        try
        {
            doLogin(uid, pwd, recepIds, msg);
        }
        catch (Exception ex)
        {
            Response.Write("Sending Failed, Please Try Again");
        }
    }

    public void doLogin(string strUserId, string strPassword, string strIds, string strMessage)
    {
        try
        {
            initRequest = (HttpWebRequest)WebRequest.Create("http://www.somewebsite.com/login.aspx");
            initRequest.CookieContainer = new CookieContainer();
            initRequest.Timeout = 60000;
            StreamReader initSr = new StreamReader(initRequest.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
            initSr.ReadToEnd();
            initSr.Close();

            loginRequest = (HttpWebRequest)WebRequest.Create("http://www.somewebsite.com/login.aspx");
            loginRequest.CookieContainer = new CookieContainer();
            loginRequest.Timeout = 60000;
            StringBuilder loginString = new StringBuilder();
            loginString.Append("LoginUserId=" + strUserId + "&LoginPassword=" + strPassword + "&RememberMe=1&Login=Login");
            byte[] loginData = Encoding.ASCII.GetBytes(loginString.ToString());
            //to get any cookies from the initial response
            initResponse = (HttpWebResponse)initRequest.GetResponse();
            //setting cookies
            loginRequest.CookieContainer.Add(initResponse.Cookies);
            //Adding Headers
            loginRequest.Method = "POST";
            loginRequest.ContentType = "application/x-www-form-urlencoded";
            loginRequest.ContentLength = loginData.Length;
            Stream loginStream = loginRequest.GetRequestStream();
            loginStream.Write(loginData, 0, loginData.Length);
            loginStream.Close();

            //Reading the response
            StreamReader loginSr = new StreamReader(loginRequest.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
            loginResponseString = loginSr.ReadToEnd();
            loginSr.Close();

            if (loginResponseString.Contains("inbox.aspx"))
            {
                //get session code
                sessionCode = loginResponseString.Substring(125, 5);
                //call the sendmessage method
                sendMessage(strIds, strMessage);

            }
            else
            {
                Response.Write("Login Failed: Check Username and password");
            }
        }
        catch (Exception ex)
        {
            Response.Write("Sending Failed, Please Try Again");
        }
    }

    public void sendMessage(string strIds, string strMsg)
    {
        try
        {
            string[] ids = strIds.Split(',');
            for (int i = 0; i < ids.Length; i++)
            {
                msgRequest = (HttpWebRequest)WebRequest.Create("http://www.somewebsite.com/writenew.aspx?sessionid=" + sessionCode);
                msgRequest.CookieContainer = new CookieContainer();
                msgRequest.Timeout = 1000000;
                msgRequest.ReadWriteTimeout = 1000000;
                msgRequest.SendChunked = true;
                //to get any cookies from the initial response
                loginResponse = (HttpWebResponse)loginRequest.GetResponse();
                //setting cookies
                msgRequest.CookieContainer.Add(loginResponse.Cookies);
                //Adding Headers
                msgRequest.Method = "POST";
                msgRequest.ContentType = "application/x-www-form-urlencoded";

                Stream msgStream = msgRequest.GetRequestStream();

                Stream respStream = msgRequest.GetResponse().GetResponseStream();

                StreamReader codeRead = new StreamReader(respStream, System.Text.Encoding.GetEncoding("utf-8"));
                string temp = codeRead.ReadToEnd();
                codeRead.Close();
                respStream.Close();
                txtResponse.Text = temp;

                try
                {
                    int starInd = temp.IndexOf("UserId_");
                    //int endInd = starInd + 15;
                    string holder = temp.Substring(starInd, 15);
                    int startInd = holder.IndexOf("_") + 1;
                    queryCode = holder.Substring(startInd, 5);
                    txtSubString.Text = queryCode;
                }
                catch (Exception ex)
                {
                    txtSubString.Text = "SOME ERROR";
                }

                lock (lockObj)
                {
                    StringBuilder msgString = new StringBuilder();
                    msgString.Append("sessionid=" + queryCode + "&GlobalKeyId=1&MessageLength=988&ReceiveId_"
                        + queryCode + "=" + ids[i] + "&Message_" + queryCode + "=" + strMsg
                        + "&SendNow_" + queryCode + "=Send Now");
                    byte[] msgData = Encoding.ASCII.GetBytes(msgString.ToString());
                    msgStream.Write(msgData, 0, msgData.Length);
                    msgStream.Close();
                }

                //Reading the response
                StreamReader msgSr = new StreamReader(respStream, System.Text.Encoding.GetEncoding("utf-8"));
                string msgResponseString = msgSr.ReadToEnd();
                msgSr.Close();
                sessionCode = msgResponseString.Substring(123, 5);
            }
            Response.Write("Message Sent Successfully");
        }
        catch (Exception ex)
        {
            Response.Write("Sending Failed, Please Try Again<br/>" + ex.Message);
        }
    }
}

The application stops when it reaches this line

msgStream.Write(msgData, 0, msgData.Length);

Please help me solve the error. Thank You

4

1 に答える 1

3

これを呼び出すGetResponse()と、これまでに構築されたリクエストが送信され、クライアントがレスポンスを取得します。

を呼び出す前に完全なリクエストを作成する必要がありますGetResponse()。そうしないと、リクエストが完了しません。リクエスト ストリームを取得し、GetResponse()が呼び出された後に POST データを書き込むと、この例外がスローされ、既に送信された後にリクエストの構築を続行しても意味がないことが示されます。

于 2013-01-01T08:41:47.853 に答える