从 Windows Phone 8 上的 HttpWebRequest 获取响应

Get Response from HttpWebRequest on Windows Phone 8

我正在尝试从 Windows Phone 应用程序对站点执行 WebRequest。 但是从服务器获得响应对我来说也很重要。 这是我的代码:

            Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
        httpWebRequest.ContentType = "application/xml; charset=utf-8";
        httpWebRequest.Method = "POST";

        using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
                                                     httpWebRequest.EndGetRequestStream, null))
        {
            string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Ahri</string>";

            byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);

            await stream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
        }

不幸的是,我不知道如何从服务器获得响应。 有人有想法吗?

提前致谢。


感谢@max,我找到了解决方案并想在上面分享。 这是我的代码的样子:

            string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Claor</string>";
        Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
        string responseFromServer = "no response";

        HttpWebRequest httpWebRequest = HttpWebRequest.Create(requestUri) as HttpWebRequest;
        httpWebRequest.ContentType = "application/xml; charset=utf-8";
        httpWebRequest.Method = "POST";



        using (Stream requestStream = await httpWebRequest.GetRequestStreamAsync())
        {
            byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);

            await requestStream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
        }

        WebResponse webResponse = await httpWebRequest.GetResponseAsync();
        using (var reader = new StreamReader(webResponse.GetResponseStream()))
        {
            responseFromServer = reader.ReadToEnd();
        }

希望对以后的人有所帮助。

This is very common question for people new in windows phone app development. There are several sites which gives tutorials for the same but I would want to give small answer here.

windows phone 8 xaml/runtime 中,您可以使用 HttpWebRequest 或一个 WebClient

Basically WebClient is a wraper around HttpWebRequest.

如果您有一个小请求,请使用 HttpWebRequest。它是这样的

HttpWebRequest request = HttpWebRequest.Create(requestURI) as HttpWebRequest;
WebResponse response = await request.GetResponseAsync();
using (var reader = new StreamReader(response.GetResponseStream()))
{
    string responseContent = reader.ReadToEnd();
    // Do anything with you content. Convert it to xml, json or anything.
}

虽然这是一个 get 请求,我看到你想做一个 post 请求,但你必须修改几个步骤才能实现。

Visit this place for post request.

如果你想要windowsphone教程,你可以去here. He writes awesome tuts.