HTTP Web请求发送两次(如何修复?)

时间:2012-02-26 06:03:46

标签: c# asp.net

我已获得以下代码来执行Web请求并获取HTTP响应。我想要做的是,如果HTTP响应是

  

200 OK

我需要阅读响应正文而不再发送网页请求(我知道我的代码目前正在发送两次)。

        try
        {
            using (WebResponse response = request.GetResponse())
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (var webClient = new WebClient())
                    {
                        string result = webClient.DownloadString(request.RequestUri);
                        if(result.StartsWith("NUMBER NOT IN LIST"))
                        {
                            return "Number Not In List";
                        }
                        return result;
                    }
                }
                else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    return statusCode = HttpStatusCode.Unauthorized.ToString();
                }
                else if (httpResponse.StatusCode == HttpStatusCode.BadRequest)
                {
                    return statusCode = HttpStatusCode.BadRequest.ToString();
                }

            }
        }

3 个答案:

答案 0 :(得分:1)

你想使用HttpWebResponse.GetResponseStream,如下所示:

HttpWebResponse.GetResponseStream Method

使用MSDN页面上的示例替换if (httpResponse.StatusCode == HttpStatusCode.OK)的内容。

答案 1 :(得分:1)

if (httpResponse.StatusCode == HttpStatusCode.OK)
{
  // we will read data via the response stream
  var resStream = httpResponse.GetResponseStream();
  var sr = new StreamReader(resStream);
  var result = sr.ReadToEnd();

}

答案 2 :(得分:1)

阅读回复流:

    try
    {
        using (WebResponse response = request.GetResponse())
        {
            HttpWebResponse httpResponse = (HttpWebResponse)response;
            if (httpResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string result = reader.ReadToEnd();
                if(result.StartsWith("NUMBER NOT IN LIST"))
                {
                    return "Number Not In List";
                }
                return result;
            }
            else if (httpResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
                return statusCode = HttpStatusCode.Unauthorized.ToString();
            }
            else if (httpResponse.StatusCode == HttpStatusCode.BadRequest)
            {
                return statusCode = HttpStatusCode.BadRequest.ToString();
            }

        }
    }