2

Windows phone 8 中的 HttpWebRequest

我正在使用 c#/xaml 开发一个 windows phone 8 应用程序。我在httpwebrequest类中遇到了一些问题。我想使用 post 方法从服务器下载数据。但是 httpwebrequest 没有按预期工作。当我随后尝试调用 Web服务时,它返回错误 (远程服务器返回错误:NotFound) 。可能是什么原因?。请帮助...以下是我的代码。

 string response = "";                 
 httpwebrequest = WebRequest.Create(new Uri(serviceurl)) as HttpWebRequest;
 httpwebrequest.Method = "POST";

            httpwebrequest.ContentType = "application/json";
            byte[] data = Serialization.SerializeData(request);

            using (var requestStream = await Task<Stream>.Factory.FromAsync(httpwebrequest.BeginGetRequestStream, httpwebrequest.EndGetRequestStream, null))
            {
                await requestStream.WriteAsync(data, 0, data.Length);
            }


            response = await httpRequest(httpwebrequest);


            var result = Serialization.Deserialize<T>(response);
            return result;


    }

    public async Task<string> httpRequest(HttpWebRequest request)
    {
        try
        {

            string received;


            using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
            {
                using (var responseStream = response.GetResponseStream())
                {
                    using (var sr = new StreamReader(responseStream))
                    {
                        received = await sr.ReadToEndAsync();
                    }
                }      

                response.Close();

            }

            return received;
        }
        catch(Exception ex)
        {
            return "";
        }
    }
4

1 回答 1

0

你检查过内部异常吗?因为我遇到了类似的问题,当我检查内部异常时,我发现我从服务器收到了另一个错误。还要检查响应标头中的真实 http 状态代码。

于 2013-04-29T10:04:16.640 回答