2011-06-02 71 views

回答

2

你必須使用HttpWebRequest對象連接到該網站,並颳去的響應信息的鏈接。

查找包含您嘗試查找的內容的html標記或類名稱,然後使用正則表達式或字符串函數來獲取所需的數據。

很好的例子here

+0

感謝您的解決方案。其實我從網站得到的迴應是HTML,在我想要的這個城市名字被返回,現在我想知道如何從這個HTML文件中獲得它? – 2011-06-02 14:17:27

+0

我會使用HTML敏捷包。 http://htmlagilitypack.codeplex.com/這裏有一個很好的例子:http://kossovsky.net/index.php/2009/07/csharp-html-parser-htmlagilitypack/ – 2011-06-02 14:19:30

0

你可以使用一個WebClient對象,並且一個簡單的方法可以用xpath來獲取數據。

2

試試這個(你需要包括System.text和System.net)

WebClient client = new WebClient(); 
string url = "http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680"; 
Byte[] requestedHTML; 
requestedHTML = client.DownloadData(url); 

UTF8Encoding objUTF8 = new UTF8Encoding(); 
string html = objUTF8.GetString(requestedHTML); 
Response.Write(html); 
+0

你應該拋棄WebClient對象if你儘管這樣做 – 2011-07-11 16:17:58

1

首先,你最好找到這個目的,一個好的Web服務。

,這是一個HttpWebRequest的例子:

HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680"); 
       httpRequest.Credentials = CredentialCache.DefaultCredentials;  
       HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse(); 

       Stream dataStream = httpResponse.GetResponseStream(); 
2

它使用重量輕在System.Net命名空間WebClient類最簡單的方法。下面的示例代碼將只需要下載一個字符串整個響應:

using (WebClient wc = new WebClient()) 
{ 
    string response = wc.DownloadString("http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680"); 
} 

但是,如果您需要在響應和請求過程中加以控制,那麼你可以使用更重的重量HttpWebRequest Class。例如,你可能想要處理不同的狀態碼或標題。在CodeProject上的文章How to use HttpWebRequest and HttpWebResponse in .NET中有一個使用HttpWebRequest的例子。