C# Windows phone获取服务器源代码
我正试图获得一个网站的源代码。在windows应用程序中,一个简单的http请求就足够了。然而,在windows phone中,它要复杂得多。 我在谷歌上搜索了很多,没有得到一个明确的答案。 这是我尝试过的,但没有大的成功C# Windows phone获取服务器源代码,c#,windows,web-services,visual-studio,windows-phone-8,C#,Windows,Web Services,Visual Studio,Windows Phone 8,我正试图获得一个网站的源代码。在windows应用程序中,一个简单的http请求就足够了。然而,在windows phone中,它要复杂得多。 我在谷歌上搜索了很多,没有得到一个明确的答案。 这是我尝试过的,但没有大的成功 public static sReturn = ""; private string _InetGetSourceCode(string sUrl) { _InetReadEx(sUrl); return sReturn; } private void _In
public static sReturn = "";
private string _InetGetSourceCode(string sUrl)
{
_InetReadEx(sUrl);
return sReturn;
}
private void _InetReadEx(string sUrl)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new
DownloadStringCompletedEventHandler(DownloadStringCallback2);
client.DownloadStringAsync(new Uri(sUrl));
}
private static void DownloadStringCallback2(Object sender,DownloadStringCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
sReturn = e.Result;
}
}
我这里做错了什么?问题是您立即返回
sReturn
,但下载要到将来某个时候才能完成。因此,在返回空字符串时,sReturn
仍然具有空字符串的默认值
您可以下载其中包含的代码,用于使用
HttpClient
便携库执行您想要执行的操作。我终于找到了问题的正确答案:
非常感谢@Peter Torr-MSFT的帮助,帮助我找到了问题的确切答案
回答
public static sReturn = "";
public async Task _InetReadEx(string sUrl)
{
try
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(new Uri(sUrl));
response.EnsureSuccessStatusCode();
//sStatus = response.StatusCode + " " + response.ReasonPhrase + Environment.NewLine;
sSource = await response.Content.ReadAsStringAsync();
sSource = sSource.Replace("<br>", Environment.NewLine); // Insert new lines
}
catch (Exception hre)
{
sSource = string.Empty;
}
}
非常感谢所有人和社区 你说的“没有大的成功”是什么意思?我只是在废弃样品,似乎什么都不起作用。似乎不起作用,比如。。。例外情况?所有数据都是大写的吗?编码问题?暂停?爆炸电话?删除了什么应用程序的高分?如果你不能对这个问题做出清晰的解释,我们将如何给出解决方案?@Petter这是有道理的。我跟着链接迷路了。我从未使用过异步方法。我会努力让它工作,然后回来。感谢you@Maria异步不是一种一次性的方法。Silverlight/Windows Phone上的开发使用异步范式来访问数据,而不管操作需要什么。有关一些实时示例,请参阅Lucian Wishik(Microsoft),它可以轻松地将自己应用于WP8平台。请尝试此视频,了解
async
编程的介绍:
public MainPage()
{
InitializeComponent();
Task.Run(async () => { await _InetReadEx("http://url.com/"); }).Wait();
}