HttpWebRequest 返回带有奇怪数字的 WebResponse
我有一个奇怪的问题。 当我收到 httpwebresquest 的响应时,一些数字出现在 html 文本的中间。
例如:
<输入类型=“隐藏”名称=“产品ID”值=“7220701403
841
89620”>
841 是一个不应该出现的数字,因此每隔几行就会出现更多。即使在开头:
c04 c04
c04 c04 html>
<头>
所以,解析html是不可能的。
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postDataString);
request.ContentLength = bytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.SendChunked = false;
using (Stream writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
response = (HttpWebResponse)request.GetResponse();
Stream remoteStream = response.GetResponseStream();
byte[] buffer = new byte[65536];
int bytesRead = 0;
do
{
bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
UTF8Encoding enc = new UTF8Encoding();
responseString += enc.GetString(buffer);
} while (bytesRead > 0);
remoteStream.Close();
html 文本位于变量responseString 中。
感谢您的任何想法和建议。
i have a strange problem.
When i get the response of a httpwebresquest, some numbers appears in the middle of the html text.
For example:
< input type="hidden" name="productid" value="7220701403
841
89620" >
That 841 is a number that should not appear, and as such are more every few rows. Even at the beginning:
c04
< html >
< head >
So, it's impossible to parse the html.
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postDataString);
request.ContentLength = bytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.SendChunked = false;
using (Stream writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
response = (HttpWebResponse)request.GetResponse();
Stream remoteStream = response.GetResponseStream();
byte[] buffer = new byte[65536];
int bytesRead = 0;
do
{
bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
UTF8Encoding enc = new UTF8Encoding();
responseString += enc.GetString(buffer);
} while (bytesRead > 0);
remoteStream.Close();
The html text is in variable responseString.
Thanks for any ideas and suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您假设服务器使用 UTF8。您也不考虑读取了多少字节(
bytesRead = remoteStream.Read(buffer, 0, buffer.Length)
),而只是将整个缓冲区转换为字符串(enc.GetString(缓冲区)
)。它应该类似于enc.GetString(buffer,0,bytesRead)
PS:还可能需要
bytesRead>=0
检查First, You assume that the server uses UTF8. You also don't consider how many bytes you read (
bytesRead = remoteStream.Read(buffer, 0, buffer.Length)
)and just convert to whole buffer to string (enc.GetString(buffer)
). It should be something likeenc.GetString(buffer,0,bytesRead)
PS: A
bytesRead>=0
check could also be needed