我是 Xamarin 的新手,我正在尝试从 Internet 获取一个简单的文本文件。我将获取文本文件并将其解析为 xml。我可以使用一些示例来解析 xml,所以我想如果我可以使用 http get 请求通过 Internet 获取文件内容就可以了。
我已经尝试了几个示例,并且经常有部分工作,但由于缺少方法定义或缺少程序集引用而无法工作。如果我能克服错误,这个例子有很大的希望(见行注释):
我的进口
using System;
using Xamarin.Forms;
using System.Threading.Tasks;
using System.IO;
using System.Net;
我遇到问题的方法:
public static async Task<string> MakeGetRequest(string url, string cookie)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request.ContentType = "text/html";
request.Method = "GET";
request.Headers ["Cookie"] = cookie;
var response = await request.GetResponseAsync ();//Type 'System.Net.HttpWebRequest' does not contain a definition for 'GetResponseAsync'
var respStream = response.GetResponseStream();
respStream.Flush ();
using (StreamReader sr = new StreamReader (respStream)) {
//Need to return this response
string strContent = sr.ReadToEnd ();
respStream = null;
return strContent;
}
}
我在 Microsoft Page 上偶然发现了这个问题的答案。
using System;
using Xamarin.Forms;
using System.Threading.Tasks;
using System.Net.Http;
using System.Diagnostics;
namespace pcl
{
public class mainPage : ContentPage
{
public mainPage ()
{
var url = "http://ohiovr.com/church_files/dayspringWesleyan/mainscreen.xml";
var myXMLstring = "";
Task task = new Task (() =>{
myXMLstring = AccessTheWebAsync (url).Result;
});
task.Start();
task.Wait();
Debug.WriteLine (myXMLstring);
Content = new StackLayout {
Children = {
new Label { Text = "Hello StackOverflow" }
}
};
}
async Task<String> AccessTheWebAsync(String url)
{
// You need to add a reference to System.Net.Http to declare client.
HttpClient client = new HttpClient();
// GetStringAsync returns a Task<string>. That means that when you await the
// task you'll get a string (urlContents).
Task<string> getStringTask = client.GetStringAsync(url);
// You can do work here that doesn't rely on the string from GetStringAsync.
//DoIndependentWork();
// The await operator suspends AccessTheWebAsync.
// - AccessTheWebAsync can't continue until getStringTask is complete.
// - Meanwhile, control returns to the caller of AccessTheWebAsync.
// - Control resumes here when getStringTask is complete.
// - The await operator then retrieves the string result from getStringTask.
string urlContents = await getStringTask;
// The return statement specifies an integer result.
// Any methods that are awaiting AccessTheWebAsync retrieve the length value.
return urlContents;
}
}
}
关于c# - Xamarin 可移植类库中的简单获取请求(我需要它在 iOS 和 Windows Phone 上运行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31493508/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |