Compact Framework中HttpWebRequest POST JSON报错:需缓冲数据完成认证/重定向
Hey there, I’ve dealt with this exact headache while building Compact Framework apps that send JSON via POST. Let’s break down why this happens and how to fix it quickly.
Why the Error Happens
Compact Framework’s HttpWebRequest has a key difference from the full .NET Framework: it disables request body buffering by default. When your request hits a scenario that needs to resend the POST data—like server authentication (e.g., Basic Auth) or an automatic redirect—the framework can’t reuse the JSON payload you sent, hence the error.
Step-by-Step Fixes
Here are the actionable steps to resolve this:
Enable Stream Buffering (Most Critical)
You need to explicitly turn on buffering so the framework can store your POST data and resend it when needed. Add this line right after creating your request:request.AllowWriteStreamBuffering = true;Handle Authentication (If Required)
If your server expects credentials, make sure to set them alongside enabling buffering. For Basic Auth, use:request.Credentials = new NetworkCredential("your-username", "your-password");For NTLM or other auth schemes, adjust the credential type accordingly.
Verify Redirect Settings
By default,AllowAutoRedirectis set totrue, but if you’re dealing with cross-protocol redirects (HTTPS → HTTP), you might need to add this (note: use cautiously, as it has security implications):request.UnsafeAuthenticatedConnectionSharing = true;
Full Working Code Example
Here’s a complete snippet that sends JSON POST data without hitting the error:
try { var request = (HttpWebRequest)WebRequest.Create("https://your-server-endpoint.com/api"); request.Method = "POST"; request.ContentType = "application/json"; request.AllowWriteStreamBuffering = true; // Enable buffering request.Credentials = new NetworkCredential("user", "pass"); // If needed // Prepare JSON payload string jsonPayload = "{\"name\": \"Test\", \"value\": 123}"; byte[] postBytes = Encoding.UTF8.GetBytes(jsonPayload); request.ContentLength = postBytes.Length; // Write data to request stream using (var requestStream = request.GetRequestStream()) { requestStream.Write(postBytes, 0, postBytes.Length); } // Get and process response using (var response = (HttpWebResponse)request.GetResponse()) using (var reader = new StreamReader(response.GetResponseStream())) { string responseText = reader.ReadToEnd(); // Do something with the response Debug.WriteLine("Response: " + responseText); } } catch (WebException ex) { // Handle errors (e.g., 401 Unauthorized, 500 Server Error) using (var errorResponse = (HttpWebResponse)ex.Response) { Debug.WriteLine("Error Status Code: " + errorResponse.StatusCode); } }
Quick Notes to Avoid Other Pitfalls
- Always set
ContentLengthto the exact length of your JSON byte array—Compact Framework is strict about this. - Use
Encoding.UTF8consistently for both sending and receiving data to avoid character encoding issues. - Catch
WebExceptionto handle server-side errors, asGetResponse()will throw exceptions for non-2xx status codes.
内容的提问来源于stack exchange,提问作者Oleksandr Khytrov

