gpt4 book ai didi

c# - System.Net.HttpWebResponse.GetResponseStream() 在 WebException 中返回截断的正文

转载 作者:太空狗 更新时间:2023-10-29 17:39:37 24 4
gpt4 key购买 nike

由于某种超出我理解的原因,对特定网站 ( https://learningnetwork.cisco.com/people/mrollins?view=profile ) 的请求导致了一个 reqsponse 对象,其响应流包含该网站的一个聚合版本。

流在 65536 字节后结束,等于 2^16 字节。我认为这是一个可疑的整数。请求提示内部服务器错误,我对此感到沮丧,因为我已经验证了网络浏览器能够理解此响应,并且完整的 html 包含在服务器的响应中。 (使用 fiddler )

我发现了之前记录的问题 here ,这是不令人满意的,原因很简单,它以这个音符结束:

"I guess I'll have to hope the error doesn't exceed 65536 characters..."

确实如此。

感谢解决方法,或者如果有人知道即将推出的修复程序也不错。

using System;
using System.IO;
using System.Net;
using System.Web.UI;

namespace Example
{
public partial class _Default : Page
{
protected void Page_Load(object senderHidden, EventArgs eHidden)
{
//ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
var cookieContainer = new CookieContainer();
//Encoding enc = Encoding.UTF8;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://learningnetwork.cisco.com/people/mrollins?view=profile");
req.AllowAutoRedirect = false;

req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
req.CookieContainer = cookieContainer;
req.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
req.Method = "GET";
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12";
req.KeepAlive = true;

HttpWebResponse resp = null;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
var r = e.Response as HttpWebResponse;
var memstream = Read(r.GetResponseStream());
var wrongLength = memstream.Length;
}
}

public static MemoryStream Read(Stream stream)
{
MemoryStream memStream = new MemoryStream();

byte[] readBuffer = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, 0, readBuffer.Length)) > 0)
memStream.Write(readBuffer, 0, bytesRead);
return memStream;
}
}
}

最佳答案

HttpWebRequest 有一个限制网络请求长度的静态属性。在发出请求之前插入的这行代码解决了问题。

HttpWebRequest.DefaultMaximumErrorResponseLength = 1048576;

关于c# - System.Net.HttpWebResponse.GetResponseStream() 在 WebException 中返回截断的正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4918107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com