gpt4 book ai didi

c# - Xamarin 可移植类库中的简单获取请求(我需要它在 iOS 和 Windows Phone 上运行)

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:40:20 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com