2012-01-20 31 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