|
本文意在教大家如何使用HttpWebRequest的POST取得网页的内容,本文以一个示例来说明这个问题,这里我要做的是,根据IP来取IP所在的地区,使用到了网址www.ip138.com这个网站。
你打开这个网站你就会发现。它有一个文本框,让你输入一个IP,然后它会给你一个相应的IP所在地区,可是它却是通过post进行传值的。我们把www.ip138.com网页的首页打开,看它的原码,你会发现,提交的时候,它会提交二个东西出去,一个是IP,一个是action的值,IP不说了,是你输入的IP值,这个action值,我分析可能是IP或是电话的分类。它是一个定值,是2。这样我们就会明白了,显示的页面是ips.asp页面,这个页面要得到的值是。ip,action好,下面是我的程序:
using System.Text; using System.IO; using System.Net这三个引用一定要引用上,不然会报错
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; using System.IO; using System.Net;
namespace GetPages { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string strId = "202.97.224.68"; string strPassword = "2";
ASCIIEncoding encoding = new ASCIIEncoding(); string postData = "ip=" + strId; postData += ("&action=" + strPassword);
byte[] data = encoding.GetBytes(postData);
// Prepare web request... HttpWebRequest myRequest =(HttpWebRequest)WebRequest.Create("http://www.ip138.com/ips.asp");
myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = data.Length; Stream newStream = myRequest.GetRequestStream();
// Send the data. newStream.Write(data, 0, data.Length); newStream.Close();
// Get response HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default); string content = reader.ReadToEnd();
string con = content.Substring(content.IndexOf("本站主数据")+6, content.IndexOf("</li><li>参考数据一") - content.IndexOf("本站主数据")-1); Response.Write(con.Trim()); } }
|