3

以下代码在 WinForms 和 Windows Phone 8 应用程序中返回错误。

代码

    var jsonData = "jsonStringGoesHere";
    var uri = new Uri("urlGoesHere");
    var webRequest = (HttpWebRequest)WebRequest.Create(uri);
    webRequest.Method = "POST";
    webRequest.ContentType = "application/json";
    webRequest.ContentLength = jsonData.Length;
    webRequest.BeginGetRequestStream(ar =>
    {
        try
        {
            using (var os = webRequest.EndGetRequestStream(ar))
            {
                var postData = Encoding.UTF8.GetBytes(jsonData);
                os.Write(postData, 0, postData.Length);
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }

        webRequest.BeginGetResponse(
            ar2 =>
            {
                try
                {
                    using (var response = webRequest.EndGetResponse(ar2))
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        var received = reader.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
            }, null);
    }, null);

WinForms 中的错误:[System.Net.WebException] = {"The remote server returned an error: (400) Bad Request."}

在 WP8The remote server returned an error: NotFound中。

WCF 服务运行良好,因为我让它们在 Fiddler 和其他类型的应用程序(如 Android/iPhone)中工作。

为什么这行不通?

4

1 回答 1

0

如果我没记错的话,我想我遇到了类似的事情。我认为它与 ContentLength 有关,但我真的不记得了。

这是我最终使用的代码。不确定它是否有帮助。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/json";
string json = BuildJSON(TestConvert(tests));
var enc = new UTF8Encoding(false);
request.ContentLength = enc.GetByteCount(json);
using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), enc))
{
    requestWriter.Write(json);
    requestWriter.Close();
}
于 2013-10-03T17:05:04.250 回答