1

所以我有一个这样的功能:

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。

我认为代码非常清晰,我看不出丢失这些字节哪里出了问题。

谢谢你的帮助!

4

2 回答 2

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;
    }
于 2013-07-08T11:58:07.687 回答
1

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

http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx

读入缓冲区的总字节数。如果当前没有那么多字节可用,则该字节数可能小于请求的字节数,如果已到达流的末尾,则该字节数为零 (0)。

msdn 示例:http WebResponse.GetResponseStream(): //msdn.microsoft.com/en-us/library/system.net.webresponse.getresponsestream.aspx

于 2013-07-08T14:20:36.177 回答