在Xamarin可移植类库中的简单Get请求(我需要它在iOS和Windows Phone上运行)
本文关键字:iOS Windows 运行 Phone 类库 可移植 Xamarin 请求 Get 简单 | 更新日期: 2023-09-27 18:03:18
我是Xamarin的新手,我正试图从互联网上获得一个简单的文本文件。我将获取文本文件并将其解析为xml。我可以用一些例子来解析xml,所以我想如果我能通过互联网使用http get请求获取文件内容,我就可以了。
我已经尝试了几个例子,经常我有部分工作的东西,但由于缺少方法定义或缺少汇编引用而无法工作。这个例子有很多承诺,如果我能克服一个错误(见行注释):
我的进口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;
}
}
我在微软网页上偶然发现了这个问题的答案
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;
}
}
}