使用url的C#web请求方法并处理流

时间:2013-05-02 20:03:52

标签: c#

您将如何使用此网络请求方法?:

        try
        {
            var request = WebRequest.Create(uri);
            using (var response = request.GetResponse())
            {
                using (var responseStream = response.GetResponseStream())
                {
                    // Process the stream
                }
            }
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError &&
                ex.Response != null)
            {
                var resp = (HttpWebResponse)ex.Response;
                if (resp.StatusCode == HttpStatusCode.NotFound)
                {
                    // Do something
                }
                else
                {
                    // Do something else
                }
            }
            else
            {
                // Do something else
            }
        }
    }

我在网站上找到了上面的代码,我不确定流意味着什么过程或者你把网址放在哪里:ex:http://www.google.com我更喜欢使用这个代码但是我不能得到其他代码使用它的陈述,这就是我需要的。

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("URL", hashe));
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        }
        catch (Exception ex)
        {
            if (ex.ToString().Contains("404"))
            {

            }
        }

1 个答案:

答案 0 :(得分:0)

您可以使用地址替换uri,或者创建名为uri的字符串变量并为其提供地址。

例如

string uri = "http://www.google.se"

但是,使用WebClient会更好。

WebClient client = new WebClient ();
string reply = client.DownloadString ("http://www.google.se");