在紧凑的框架中POST HttpWebRequest

问题描述 投票:0回答:1

我正在开发紧凑框架中的应用程序,需要将POST一个Json发送到服务器

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

    }

异常错误

此请求需要缓冲数据以进行身份​​验证或重定向才能成功。

c# compact-framework windows-ce motorola-emdk system.net.httpwebrequest
1个回答
1
投票

我自己对HttpClient比较熟悉并且从未使用过HttpWebRequest,但是我收到的任何有关重定向的错误都可以通过确保您的URL完全正确来快速解决。

var url = WorkSettings.URL + "savedoc/" + document.DocType + "/" + document.DocNumber

确保您上面的网址正是您要保存到的网址。也许你在发生错误的URL中添加了一个额外的“/”?或者您可能需要将“.php”或“.html”附加到网址的末尾。

如果您无法调试代码以逐步查看此确切的URL,则还可以在发生重定向请求时使用Wireshark或Fiddler视图。

其他需要考虑的问题:

1)如果发送错误的URL,是否要进行自动重定向?可能,但也许不是。如果没有,值得指出的是HttpWebRequest的AutoRedirect property默认设置为true。

2)你想具体处理这个错误吗?或者错误不是由于URL略微不正确造成的。如果是这样,我在处理此错误方面没有太多个人经验。也许this StackOverflow post有一个非常简单的解决方案,可能会做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.