开发者

HttpWebRequest is getting stream even without internet connection

I am using below code to send a byte array to a site. Why this code is not throwing an exception even when there is no internet connection?.Even when no connection is there I am able to get stream and able to write to it.I expect it to throw an exce开发者_如何学Pythonption at Stream postStream = request1.EndGetRequestStream(result).Anyone got any idea why its behaving like this.

     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);
            }
        }


I expect it's buffering everything until you're done writing, at which point it will be able to use the content length immediately. If you set:

request.AllowWriteStreamBuffering = false;

then I suspect it will fail at least when you write to the stream.

Btw, your calculation of the required length for postArray appears to be assuming one byte per character, which won't always be the case... and you're calling ToString on postBody which looks like it's redundant. I'm not sure why you're trying to write in a single call anyway... either you could call Write three times:

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

or (preferrably) just use a StreamWriter:

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

It's also unclear why you've added 1 to the required length when initializing postArray. Are you trying to send an extra "0" byte at the end of the data?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜