xamarin android从webservice接收一个简单的句子/字符串

时间:2017-11-18 16:46:21

标签: xamarin.android httprequest

我试图从网络服务中收到一个简单的句子,但我有些不对劲。

这是我从webservice请求的异步任务:

private async Task<string> GetData (string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri(url));
        request.ContentType = "text/plain";
        request.Method = "GET";

        using (WebResponse response = await request.GetResponseAsync())
        {
            using (Stream stream = response.GetResponseStream())
            {
                string doc = await Task.Run(() => stream.ToString());
                return doc;
            }
        }

    }

这是我的按钮:

cmd02.Click += async (sender, e) => {
            string sentence = await GetData(url);
            txt01.Text = sentence;
        };

我只将“System.Net.WebConnectionStream”添加到我的TextView中,不知道应该使用哪个函数。或者可能是错误的?

也许有人有想法?

1 个答案:

答案 0 :(得分:1)

public static async Task<string> SendGetRequestAsync (string url) {

            string responseString = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
            request.Method = WebRequestMethods.Http.Get;
            HttpWebResponse response;

            await Task.Run (() => {
                try {
                    response = request.GetResponse () as HttpWebResponse;
                    using (var reader = new StreamReader (response.GetResponseStream ())) {
                        responseString = reader.ReadToEnd ();
                    }
                } catch (WebException ex) {

                    Console.WriteLine (ex);
                }
            });

            return responseString;
        }