WebException.Response.GetResponseStream() 限制为 65536 个字符
我正在尝试使用 HttpWebRequest 和 HttpWebResponse 从网页检索 HTML 代码。
response = (HttpWebResponse)request.GetResponse();
...
Stream stream = response.GetResponseStream();
响应对象的 ContentLength 值为 106142。当我查看流对象时,它的长度为 65536。当使用 ReadToEnd() 通过 StreamReader 读取流时,仅返回前 65536 个字符。
我怎样才能得到完整的代码?
编辑:
使用以下代码段:
catch (WebException ex)
{
errorMessage = errorMessage + ex.Message;
if (ex.Response != null) {
if (ex.Response.ContentLength > 0)
{
using (Stream stream = ex.Response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
string pageOutput = reader.ReadToEnd().Trim();
ex.Response.ContentLength = 106142
ex.Response.GetResponseStream().Length = 65536
stream.Length = 65536
pageOutput.Length = 65534 (由于修剪)
是的,代码实际上被截断了。
I am trying to retrieve HTML code from a webpage using HttpWebRequest and HttpWebResponse.
response = (HttpWebResponse)request.GetResponse();
...
Stream stream = response.GetResponseStream();
The response object has a ContentLength value of 106142. When I look at the stream object, it has a length of 65536. When reading the stream with a StreamReader using ReadToEnd(), only the first 65536 characters are returned.
How can I get the whole code?
Edit:
Using the following code segment:
catch (WebException ex)
{
errorMessage = errorMessage + ex.Message;
if (ex.Response != null) {
if (ex.Response.ContentLength > 0)
{
using (Stream stream = ex.Response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
string pageOutput = reader.ReadToEnd().Trim();
ex.Response.ContentLength = 106142
ex.Response.GetResponseStream().Length = 65536
stream.Length = 65536
pageOutput.Length = 65534 (because of the trim)
And yes, the code is actually truncated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在 System.Net.HttpWebResponse 中找到本主题的答案.GetResponseStream() 在 WebException 中返回截断的正文
您必须管理
HttpWebRequest
对象并更改DefaultMaximumErrorResponseLength
属性。例如 :
You can find an answer in this topic in System.Net.HttpWebResponse.GetResponseStream() returns truncated body in WebException
You have to manage the
HttpWebRequest
object and changeDefaultMaximumErrorResponseLength
property.For example :
ReadToEnd 就是专门这样做的,它读取到流的末尾。我会检查以确保您确实收到了完整的预期回复。
ReadToEnd does specifically just that, it reads to the end of the stream. I would check to make sure that you were actually being sent the entire expected response.
对异常返回的 HttpWebResponse 调用 GetResponseStream() 方法时似乎出现问题。当没有例外时,一切都会按预期进行。
我想从服务器返回的错误中获取 HTML 代码。
我想我必须希望错误不超过 65536 个字符......
There seems to be a problem when calling the GetResponseStream() method on the HttpWebResponse returned by the exception. Everything works as expected when there is no exception.
I wanted to get the HTML code from the error returned by the server.
I guess I'll have to hope the error doesn't exceed 65536 characters...