我试图从网络服务中收到一个简单的句子,但我有些不对劲。
这是我从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中,不知道应该使用哪个函数。或者可能是错误的?
也许有人有想法?
答案 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;
}