C#WebResponse流丢失字节?

时间:2013-07-08 08:26:19

标签: c# json stream byte webresponse

所以我有这样的功能:

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字节[3949]到字节[4745]的全部为0,但应填充它们。因此,UTF8 JSON字符串提前中断,我无法反序列化我的JSON。

我认为代码非常明确,我看不出丢失这些字节的错误。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

我使用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;
    }

答案 1 :(得分:1)

从流中读取时,您可以获得的字节数少于请求的数量。

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