C# 紧凑框架中的PostHttpWebRequest
我正在compact框架中开发应用程序,需要向服务器发送一个Json帖子C# 紧凑框架中的PostHttpWebRequest,c#,compact-framework,windows-ce,motorola-emdk,system.net.httpwebrequest,C#,Compact Framework,Windows Ce,Motorola Emdk,System.net.httpwebrequest,我正在compact框架中开发应用程序,需要向服务器发送一个Json帖子 public SResponse SaveDoc(Document document) { var url = WorkSettings.URL + "savedoc/" + document.DocType + "/" + document.DocNumber; string json = JsonConvert.SerializeObject(document);
public SResponse SaveDoc(Document document)
{
var url = WorkSettings.URL + "savedoc/" + document.DocType + "/" + document.DocNumber;
string json = JsonConvert.SerializeObject(document);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
// turn our request string into a byte stream
byte[] postBytes;
if (json != null)
{
postBytes = Encoding.UTF8.GetBytes(json);
}
else
{
postBytes = new byte[0];
}
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
// now send it
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
return GetResponseData(response);
}
异常错误
此请求需要缓冲数据,以使身份验证或重定向成功
我对自己比较熟悉,也从未使用过HttpWebRequest,但我在处理重定向时遇到的任何错误都可以通过确保您的URL完全正确而迅速得到解决
var url = WorkSettings.URL + "savedoc/" + document.DocType + "/" + document.DocNumber
确保上面的URL正是您试图保存到的URL。可能是您在发生错误的URL中添加了一个额外的/?或者,您可能需要在url的末尾附加.php或.html
如果您无法调试代码以逐步了解这个确切的URL,那么如果发生重定向请求,您也可以使用Wireshark或Fiddler视图
需要考虑的其他问题:
1如果发送错误的URL,是否希望自动重定向?可能,但可能不是。如果不是,那么值得指出的是,HttpWebRequest的默认设置为true
2您想专门处理此错误吗?或者,该错误可能不是由于URL稍有错误而导致的。如果是这样的话,我个人没有太多处理这个错误的经验。也许有一个非常简单的解决方案可以做到这一点。最后我发现url是区分大小写的。url.ToLower解决了这个问题