Windows phone 获取服务器源代码
Windows phone get server source code
我正在尝试获取站点的源代码。在 windows 应用程序中,一个简单的 http 请求就足够了。但是在 windows phone 中要复杂得多。
我在 google 上搜索了很多,但没有得到明确的答案。
这是我尝试过但没有大成功的方法。
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;
}
}
我做错了什么?
问题是您 return sReturn
立即下载,但要等到将来某个时间才能完成下载。所以sReturn
在你return它的时候仍然有空字符串的默认值。
您可以下载 this sample,其中包含使用 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;
}
}
以及调用方式:
public MainPage()
{
InitializeComponent();
Task.Run(async () => { await _InetReadEx("http://url.com/"); }).Wait();
}
非常感谢大家和社区!
我正在尝试获取站点的源代码。在 windows 应用程序中,一个简单的 http 请求就足够了。但是在 windows phone 中要复杂得多。 我在 google 上搜索了很多,但没有得到明确的答案。 这是我尝试过但没有大成功的方法。
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;
}
}
我做错了什么?
问题是您 return sReturn
立即下载,但要等到将来某个时间才能完成下载。所以sReturn
在你return它的时候仍然有空字符串的默认值。
您可以下载 this sample,其中包含使用 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;
}
}
以及调用方式:
public MainPage()
{
InitializeComponent();
Task.Run(async () => { await _InetReadEx("http://url.com/"); }).Wait();
}
非常感谢大家和社区!