现在的位置: 首页 > 综合 > 正文

使用HttpWebRequest的POST取得网页内容

2012年11月20日 ⁄ 综合 ⁄ 共 2147字 ⁄ 字号 评论关闭
 这里我要做的是,根据IP来取IP所在的地区,使用网址www.ip138.com这个网站。
你打开这个网站你就会发现。它有一个文本框,让你输入一个IP,然后它会给你一个相应的IP所在地区,可是它却是通过post进行传值的。我们把www.ip138.com网页的首页打开,看它的原码,你会发现,提交的时候,它会提交二个东西出去,一个是IP,一个是action的值,IP不说了,是你输入的IP值,这个action值,我分析可能是IP或是电话的分类。它是一个定值,是2。这样我们就会明白了,显示的页面是ips.asp页面,这个页面要得到的值是。ip,action好,下面是我的程序
  1. using System.Text;
  2. using System.IO;
  3. using System.Net这三个引用一定要引用上,不然会报错

  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Collections;
  5. using System.Web;
  6. using System.Web.Security;
  7. using System.Web.UI;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.Web.UI.HtmlControls;
  11. using System.Text;
  12. using System.IO;
  13. using System.Net;
  14. namespace GetPages
  15. {
  16.     public partial class WebForm1 : System.Web.UI.Page
  17.     {
  18.         protected void Page_Load(object sender, EventArgs e)
  19.         {
  20.             if (!Page.IsPostBack)
  21.             {
  22.                 string strId = "202.97.224.68";
  23.                 string strPassword = "2";
  24.                 ASCIIEncoding encoding = new ASCIIEncoding();
  25.                 string postData = "ip=" + strId;
  26.                 postData += ("&action=" + strPassword);
  27.                 byte[] data = encoding.GetBytes(postData);
  28.                 // Prepare web request...
  29.                 HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create("http://www.ip138.com/ips.asp");
  30.                 myRequest.Method = "POST";
  31.                 myRequest.ContentType = "application/x-www-form-urlencoded";
  32.                 myRequest.ContentLength = data.Length;
  33.                 Stream newStream = myRequest.GetRequestStream();
  34.                 // Send the data.
  35.                 newStream.Write(data, 0, data.Length);
  36.                 newStream.Close();
  37.                 // Get response
  38.                 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
  39.                 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
  40.                 string content = reader.ReadToEnd();
  41.                 string con = content.Substring(content.IndexOf("本站主数据")+6, content.IndexOf("</li><li>参考数据一") - content.IndexOf("本站主数据")-1);
  42.                 Response.Write(con.Trim()); 
  43.             }
  44.         }
  45.    

抱歉!评论已关闭.