所以我有一个这样的函数:
private String SendRequest(String jsonRequest)
{
WebRequest webRequest = WebRequest.Create(_url);
byte[] paramBytes = Encoding.UTF8.GetBytes(jsonRequest);
byte[] responseBytes;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.ContentLength = paramBytes.Length;
webRequest.Headers.Add("X-Transmission-Session-Id", _sessionId);
using (Stream oStream = webRequest.GetRequestStream())
{
oStream.Write(paramBytes, 0, paramBytes.Length);
}
WebResponse webResponse = webRequest.GetResponse();
using (Stream iStream = webResponse.GetResponseStream())
{
responseBytes = new byte[webResponse.ContentLength];
iStream.Read(responseBytes, 0, (int) webResponse.ContentLength);
}
return Encoding.UTF8.GetString(responseBytes);
}
问题是,在iStream.Read()阶段,一些字节丢失了。使用wireshark显示所有的字节都被发送到了这台机器上,然而.Net在这一过程中的某个地方丢失了它们。例如,在我当前的调试会话中,webResponse.ContentLength=4746 byte[3949]到byte[4745]都是0,但它们应该被填充。因此,UTF8 JSON字符串很早就断开了,我无法取消JSON的序列化。
我认为代码非常清晰,我看不出丢失这些字节有什么错。
谢谢你的帮助!
从流中读取时,可以获得比请求更少的字节。
http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx
读取到缓冲区的总字节数。这可能小于如果当前没有那么多字节,则请求的字节数可用,或者如果已经到达流的末尾则为零(0)。
WebResponse.GetResponseStream()
的msdn示例:http://msdn.microsoft.com/en-us/library/system.net.webresponse.getresponsestream.aspx
我改为使用StreamReader修复了它:)
private String SendRequest(String jsonRequest)
{
WebRequest webRequest = WebRequest.Create(_url);
byte[] paramBytes = Encoding.UTF8.GetBytes(jsonRequest);
String jsonResponse;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.ContentLength = paramBytes.Length;
webRequest.Headers.Add("X-Transmission-Session-Id", _sessionId);
using (Stream oStream = webRequest.GetRequestStream())
{
oStream.Write(paramBytes, 0, paramBytes.Length);
oStream.Close();
}
WebResponse webResponse = webRequest.GetResponse();
using (Stream iStream = webResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(iStream, Encoding.UTF8);
jsonResponse = reader.ReadToEnd();
reader.Close();
iStream.Close();
}
return jsonResponse;
}