无法从HTTPS读取HttpResponse

时间:2013-01-10 18:07:53

标签: c# https

public void HttpsRequest(string address)
    {
        string data;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
        request.Method = "GET";

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        byte[] resp = new byte[(int)response.ContentLength];
        Stream receiveStream = response.GetResponseStream();
        using (StreamReader reader = new StreamReader(receiveStream, Encoding.ASCII))
        {
            data = reader.ReadToEnd();
        }
    }

当我尝试通过https读取页面时,我得到算术运算导致溢出。发生错误是因为响应给了我ContentLenght = -1。 使用fiddler我可以看到页面已收到。其他一些使用HTTPS的网站运行正常,但大多数没有。

3 个答案:

答案 0 :(得分:1)

如果我查询https://www.google.com,我会收到相同的错误消息,因为并非每个响应都有内容长度。使用此代码可以避免此问题:

public static void HttpsRequest(string address)
{
  string data;
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
   request.Method = "GET";

   using (WebResponse response = request.GetResponse())
  {
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        data = reader.ReadToEnd();
    }
  }
}

答案 1 :(得分:0)

此行为是预期的:并非每个响应都包含内容长度。

您的样本中没有任何内容需要知道长度,所以根本不能阅读它。

答案 2 :(得分:0)

来自HttpWebResponse.ContentLength Property

The ContentLength property contains the value of the Content-Length header returned with the response. If the Content-Length header is not set in the response, ContentLength is set to the value -1.

如果未设置Content-Length标题,则表示您的回复不正确。