WebRequest不工作

时间:2013-10-03 15:36:49

标签: c# json wcf webrequest

以下代码在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."}

在WP8中The remote server returned an error: NotFound

WCF服务正常运行,因为我让它们在Fiddler以及其他类型的应用程序(如Android / iPhone)中运行。

为什么这不起作用?

1 个答案:

答案 0 :(得分: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();
}