2012-01-20 32 views
0

我想使用預定義的cookie導航到網站, 向input type="text"的幾個添加一些文本,並使用提交按鈕提交表單。 我知道這可以做到,但我無法找到。webBrowser Cookie和表單提交

我已經嘗試將POST數據發送到頁面,但我必須單擊要執行的操作的按鈕。 這裏是我的代碼:

 static String readHtmlPage(string url) 
     { 

     //setup some variables 

     String username = "demo"; 
     String password = "password"; 
     String firstname = "John"; 
     String lastname = "Smith"; 

     //setup some variables end 

     String result = ""; 
     String strPost = "username=" + username + "&password=" + password + "&firstname=" + firstname + "&lastname=" + lastname; 
     StreamWriter myWriter = null; 

     HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url); 
     objRequest.Headers["Cookie"] = "sid=0"; 
     objRequest.Headers["Cookie"] = "username=0"; 
     objRequest.Method = "POST"; 
     objRequest.ContentLength = strPost.Length; 
     objRequest.ContentType = "application/x-www-form-urlencoded"; 

     try 
     { 
      myWriter = new StreamWriter(objRequest.GetRequestStream()); 
      myWriter.Write(strPost); 
     } 
     catch (Exception e) 
     { 
      return e.Message; 
     } 
     finally 
     { 
      myWriter.Close(); 
     } 

     HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse(); 
     using (StreamReader sr = 
      new StreamReader(objResponse.GetResponseStream())) 
     { 
      result = sr.ReadToEnd(); 

      // Close and clean up the StreamReader 
      sr.Close(); 
     } 
     return result; 
    } 


    static void Main(string[] args) 
    { 

     Console.Write(readHtmlPage("http://www.ggogle.com/")); 
    } 

回答

0

我的建議,這是我在過去所做的就是:
- 使用提琴手,並與您的瀏覽器中點擊該網站,填寫你喜歡的形式通常會。
- Fiddler會記錄請求/響應,您可以複製發佈數據字符串並替換您需要的任何值,然後使用HttpWebRequest/HttpWebResponse以編程方式執行POST並獲得響應。

post data through httpWebRequest

舉例:這裏是我提交最後評論我捕捉後的數據。

comment=When+you+collect+the+recorded+POST+string+you+can+swap+out+the+key+value+pairs+in+there+before+you+make+the+request.+When+the+OnClick+event+fires+it+will+POST+data+to+the+server%2C+this+is+what+you+need+to+recreate+nothing+with+the+javascript.&fkey=62a7d57a52ee7fa723413a2e1dbe7e71

string postData = string.format("comment={0}&fkey={1}", myCommentString, myFKey); 

然後,您可以通過這個字符串的URL的POST反對和使用的HttpWebRequest重新創建它。

您還需要確保您的URL是在後字符串中對您的值進行編碼。

+0

我需要每次發送不同的值。 如果我發送POST數據,它不起作用,因爲該動作綁定到提交按鈕的OnClick事件。 – user1161257

+0

收集記錄的POST字符串時,您可以在發出請求之前將其中的鍵值對換出。當OnClick事件觸發時,它會將數據發佈到服務器,這就是你需要用javascript重新創建的東西。 – user1231231412

+0

我愛你,謝謝。 – user1161257