如何阅读网站的回复?

时间:2011-06-02 13:10:19

标签: c# asp.net

我有一个网站网址,它通过将邮政编码作为输入参数来提供相应的城市名称。现在我想知道如何阅读网站的回复。

这是我使用的链接http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680

7 个答案:

答案 0 :(得分:2)

您必须使用HTTPWebRequest对象连接到站点并从响应中获取信息。

查找包含您要查找的内容的html标记或类名,然后使用正则表达式或字符串函数来获取所需的数据。

好例子here

答案 1 :(得分: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);

答案 2 :(得分: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的示例。

答案 3 :(得分:1)

使用WebClient类(http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=VS.100%29.aspx)来请求页面并以字符串形式获取响应。

        WebClient wc = new WebClient();
        String s = wc.DownloadString(DestinationUrl);

您可以使用String.IndexOf,SubString等正则表达式搜索特定HTML的响应,或者尝试专门为帮助解析HTML而创建的HTML Agility Pack(http://htmlagilitypack.codeplex.com/)。

答案 4 :(得分: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();

答案 5 :(得分:0)

您需要使用HttpWebRequest接收内容和一些工具来解析HTML并找到您需要的内容。在c#中使用html最流行的lib之一是HtmlAgilityPack,你可以在这里看到简单的例子:http://www.fairnet.com/post/2010/08/28/Html-screen-scraping-with-HtmlAgilityPack-Library.aspx

答案 6 :(得分:0)

您可以使用WebClient对象,并且使用xpath轻松获取数据。

相关问题