即使没有互联网连接,HttpWebRequest也会获得流

时间:2011-04-13 08:44:13

标签: c# windows-phone-7 httpwebrequest

我使用下面的代码将字节数组发送到站点。为什么即使没有互联网连接,这段代码也不会抛出异常?。即使没有连接,我也能获得流并能够写入它。我希望它在Stream postStream = request1.EndGetRequestStream(result)处抛出异常。任何人都知道为什么它的表现如此。

     private void UploadHttpFile()
    {
        HttpWebRequest request = WebRequest.CreateHttp(new Uri(myUrl));
        request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);


        request.UserAgent = "Mozilla/4.0 (Windows; U; Windows Vista;)";

        request.Method = "POST";
        request.UseDefaultCredentials = true;

        request.BeginGetRequestStream(GetStream, request);


    }

    private void GetStream(IAsyncResult result)
    {
        try
        {
            HttpWebRequest request1 = (HttpWebRequest)result.AsyncState;
            using (Stream postStream = request1.EndGetRequestStream(result))
            {
                int len = postBody.Length;
                len += mainBody.Length;
                len += endBody.Length;
                byte[] postArray = new byte[len + 1];
                Encoding.UTF8.GetBytes(postBody.ToString()).CopyTo(postArray, 0);
                Encoding.UTF8.GetBytes(mainBody).CopyTo(postArray, postBody.Length);
                Encoding.UTF8.GetBytes(endBody).CopyTo(postArray, postBody.Length + mainBody.Length);
                postStream.Write(postArray, 0, postArray.Length);
            }
        }

1 个答案:

答案 0 :(得分:2)

我希望它在你完成写作之前缓冲所有内容,此时它将能够立即使用内容长度。如果你设置:

request.AllowWriteStreamBuffering = false;

然后我怀疑它至少在你写入流时会失败。

顺便说一句,你对postArray所需长度的计算似乎假设每个字符有一个字节,但情况并非总是如此......你在{{ToString上调用postBody 1}} 看起来就像它是多余的。我不确定你为什么要在一个电话中写一个... 要么你可以拨打三次电话:

byte[] postBodyBytes = Encoding.UTF8.GetBytes(postBody);
postStream.Write(postBodyBytes, 0, postBodyBytes.Length);
// etc

(最好)只使用StreamWriter

using (Stream postStream = request1.EndGetRequestStream(result))
{
    using (StreamWriter writer = new StreamWriter(postStream)
    {
        writer.Write(postBody);
        writer.Write(mainBody);
        writer.Write(endBody);
    }
}

还不清楚为什么在初始化postArray时为什么要将1添加到所需的长度。您是否尝试在数据末尾发送额外的“0”字节?