English 中文(简体)
Why am I running out of bytes for the stream while performing an HTTP POST?
原标题:

This is driving me nuts:

    WebRequest request = WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = Encoding.UTF8.GetByteCount(data);
    Stream reqs = request.GetRequestStream();
    StreamWriter stOut = new StreamWriter(reqs, Encoding.UTF8);
    stOut.Write(data);
    stOut.Flush();

I get an exception that I ve run out of bytes in the stream...but I ve used the same encoding to get the byte count!

Using ASCII this doesn t fail. Is this because of the UTF-8 BOM that Windows likes to add in?

最佳回答

This is probably the BOM; try using an explicit encoding without a BOM:

Encoding enc = new UTF8Encoding(false);
...
request.ContentLength = enc.GetByteCount(data);
...
StreamWriter stOut = new StreamWriter(reqs, enc);

Even easier; switch to WebClient instead and of trying to handle it all yourself; it is very easy to post a form with this:

    using (var client = new WebClient())
    {
        var data = new NameValueCollection();
        data["foo"] = "123";
        data["bar"] = "456";
        byte[] resp = client.UploadValues(address, data);
    }

Or with the code from here:

  byte[] resp = client.Post(address, new {foo = 123, bar = 546});
问题回答

You can also try something like this:

byte[] bytes = Encoding.UTF8.GetBytes(data);

request.ContentLength = bytes.Length;
request.GetRequestStream().Write(bytes, 0, bytes.Length);

Don t forget to actually URL-encode the data, like you promised in the ContentType. It s a one-liner:

byte[] bytes = System.Web.HttpUtility.UrlEncodeToBytes(data, Encoding.UTF8);




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签