从 txt 文件中加载 URL 并在浏览器同步 WebClient httpRequest 中加载 URL [英] Load URL from txt File and load the URL in Browser Synchronous WebClient httpRequest
问题描述
我用微软的这个例子开始了 Windows Phone 编程:http://code.msdn.microsoft.com/wpapps/Hybrid-Web-App-75b7ef74/view/SourceCode
该应用仅显示浏览器并加载 URL.
现在我想直接从 .txt 文件加载另一个 URL.例如:http://www.test.de/appurl.txt 然后我想在 Windows Phone 应用程序中加载 URL.--> 例如:http://anotherserver.de/index.html?mobileApp>
我的问题是,URL 必须同步加载而不是异步加载.我实现了一个 AutoResetEvent,但它不起作用...
希望有人能帮助我,谢谢!
这是我的代码:
公共部分类 MainPage : PhoneApplicationPage{//URL zur WebApp//TODO: URL muss aus diesem TEXT-File ausgelesen werden!私有字符串_appURL = "http://www.test.de/appurl.txt";公共字符串_homeURL =";//私有字符串_homeURL = "http://anotherserver.de/index.html?mobileApp";//URL zur Registrierung von Angeboten私有字符串_registrationURL = "http://anotherserver.de/index.html?bereich=registrierung&mobileApp";//二级瓦片数据//私有Uri _currentURL;//私有Uri _tileImageURL;//私有字符串_pageTitle = "Shop";//在停用时将 URL 序列化为 IsoStorage 以实现快速应用程序恢复私有 Uri _deactivatedURL;私有IsolatedStorageSettings _userSettings = IndependentStorageSettings.ApplicationSettings;//指示我们何时导航到新页面.私人 ProgressIndicator _progressIndicator;//构造函数公共主页(){初始化组件();//从txt文件中读取URL并设置_homeURL读取文件(_appURL);//设置进度指示器_progressIndicator = new ProgressIndicator();_progressIndicator.IsIndeterminate = true;_progressIndicator.IsVisible = false;SystemTray.SetProgressIndicator(this, _progressIndicator);//硬件后退键的事件处理程序BackKeyPress += MainPage_BackKeyPress;//快速应用恢复事件PhoneApplicationService.Current.Deactivated += Current_Deactivated;PhoneApplicationService.Current.Closing += Current_Closing;}//AutoResetEvent are = new AutoResetEvent(false);public void ReadFile(字符串地址){var webClient = new WebClient();webClient.OpenReadAsync(new Uri(address));webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);//锁定线程直到网络调用完成//are.WaitOne();//最后调用NotifyComplete方法结束后台代理//通知完成();}void webClient_OpenReadCompleted(对象发送者,OpenReadCompletedEventArgs e){尝试{使用 (var reader = new StreamReader(e.Result)){下载的字符串 = reader.ReadToEnd();Debug.WriteLine("下载= " + 下载);_homeURL = 下载;//工作=假;}}抓住{Debug.WriteLine("请检查您的数据连接");MessageBox.Show("请检查您的数据连接");}//信号锁定线程现在可以继续//are.Set();}#region 应用导航事件protected override void OnNavigatedTo(NavigationEventArgs e){base.OnNavigatedTo(e);//浏览器事件处理程序Browser.Navigating += Browser_Navigating;Browser.Navigated += Browser_Navigated;Browser.NavigationFailed += Browser_NavigationFailed;Browser.IsScriptEnabled = true;//尝试获取为快速应用恢复存储的 URL.尝试{_deactivatedURL = (Uri)(_userSettings["deactivatedURL"]);}catch (System.Collections.Generic.KeyNotFoundException keyNotFound){Debug.WriteLine(keyNotFound.Message);}//我们是从一个固定的瓷砖开始的吗?if (NavigationContext.QueryString.ContainsKey("StartURL")){//导航到固定页面.Browser.Navigate(new Uri(NavigationContext.QueryString["StartURL"], UriKind.RelativeOrAbsolute));}否则 if ((_deactivatedURL != null) && (e.NavigationMode != NavigationMode.Reset)){//如果有我们上次存储的 URL//会话被停用,导航到那里if (Browser.Source != _deactivatedURL){Browser.Navigate(_deactivatedURL);}}别的{//不是从固定磁贴启动...//上次停用应用程序时没有存储的 URL...//所以,只需导航到主页Browser.Navigate(new Uri(_homeURL, UriKind.RelativeOrAbsolute));}}....
我的问题是,URL 必须同步加载而不是异步加载
不,你不能同步进行,但使用 async/await
你可以假装它.
为此,您可以使用类似这样的方法(您甚至可以将其编写为扩展方法)
await Navigate(webBrowser1, "http://stackoverflow.com");DoSomethingAfterNavigationCompleted();
<小时>
Task Navigate(WebBrowser wb,string url){var tcs = new TaskCompletionSource
I started Windows Phone programming with this example from Microsoft: http://code.msdn.microsoft.com/wpapps/Hybrid-Web-App-75b7ef74/view/SourceCode
The app only displays the browser and load a URL.
Now I want to load an other URL directly from a .txt file. For example: http://www.test.de/appurl.txt and then I want to load the URL in the Windows Phone App. --> For example: http://anotherserver.de/index.html?mobileApp
My problem is, that the URL have to load synchronous and not asynchronous. I implement a AutoResetEvent, but it don´t work...
Hope somebody can help me, thx!
Here is my Code:
public partial class MainPage : PhoneApplicationPage
{
// URL zur WebApp
// TODO: URL muss aus diesem TEXT-File ausgelesen werden!
private string _appURL = "http://www.test.de/appurl.txt";
public string _homeURL = "";
//private string _homeURL = "http://anotherserver.de/index.html?mobileApp";
// URL zur Registrierung von Angeboten
private string _registrationURL = "http://anotherserver.de/index.html?bereich=registrierung&mobileApp";
// Secondary tile data
//private Uri _currentURL;
//private Uri _tileImageURL;
//private string _pageTitle = "Shop ";
// Serialize URL into IsoStorage on deactivation for Fast App Resume
private Uri _deactivatedURL;
private IsolatedStorageSettings _userSettings = IsolatedStorageSettings.ApplicationSettings;
// To indicate when we're navigating to a new page.
private ProgressIndicator _progressIndicator;
// Constructor
public MainPage()
{
InitializeComponent();
//Read the URL from a txt file and set the _homeURL
ReadFile(_appURL);
// Setup the progress indicator
_progressIndicator = new ProgressIndicator();
_progressIndicator.IsIndeterminate = true;
_progressIndicator.IsVisible = false;
SystemTray.SetProgressIndicator(this, _progressIndicator);
// Event handler for the hardware back key
BackKeyPress += MainPage_BackKeyPress;
// Fast app resume events
PhoneApplicationService.Current.Deactivated += Current_Deactivated;
PhoneApplicationService.Current.Closing += Current_Closing;
}
//AutoResetEvent are = new AutoResetEvent(false);
public void ReadFile(string address)
{
var webClient = new WebClient();
webClient.OpenReadAsync(new Uri(address));
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
// lock the thread until web call is completed
//are.WaitOne();
//finally call the NotifyComplete method to end the background agent
//NotifyComplete();
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
using (var reader = new StreamReader(e.Result))
{
string downloaded = reader.ReadToEnd();
Debug.WriteLine("downloaded= " + downloaded);
_homeURL = downloaded;
//work = false;
}
}
catch
{
Debug.WriteLine("Please check your data connection");
MessageBox.Show("Please check your data connection");
}
//signals locked thread that can now proceed
//are.Set();
}
#region App Navigation Events
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
// Browser event handlers
Browser.Navigating += Browser_Navigating;
Browser.Navigated += Browser_Navigated;
Browser.NavigationFailed += Browser_NavigationFailed;
Browser.IsScriptEnabled = true;
// Try to get the URL stored for fast app resume.
try
{
_deactivatedURL = (Uri)(_userSettings["deactivatedURL"]);
}
catch (System.Collections.Generic.KeyNotFoundException keyNotFound)
{
Debug.WriteLine(keyNotFound.Message);
}
// Were we started from a pinned tile?
if (NavigationContext.QueryString.ContainsKey("StartURL"))
{
// Navigate to the pinned page.
Browser.Navigate(new Uri(NavigationContext.QueryString["StartURL"], UriKind.RelativeOrAbsolute));
}
else if ((_deactivatedURL != null) && (e.NavigationMode != NavigationMode.Reset))
{
// If there is a stored URL from our last
// session being deactivated, navigate there
if (Browser.Source != _deactivatedURL)
{
Browser.Navigate(_deactivatedURL);
}
}
else
{
// Not launched from a pinned tile...
// No stored URL from the last time the app was deactivated...
// So, just navigate to the home page
Browser.Navigate(new Uri(_homeURL, UriKind.RelativeOrAbsolute));
}
}
....
My problem is, that the URL have to load synchronous and not asynchronous
No you can't do it synchronously, but using async/await
you can pretend it.
For this, You can use a method something like this (you can even write it as an extension method)
await Navigate(webBrowser1, "http://stackoverflow.com");
DoSomethingAfterNavigationCompleted();
Task Navigate(WebBrowser wb,string url)
{
var tcs = new TaskCompletionSource<object>();
WebBrowserDocumentCompletedEventHandler documentCompleted = null;
documentCompleted = (o, s) =>
{
wb.DocumentCompleted -= documentCompleted;
tcs.TrySetResult(null);
};
wb.DocumentCompleted += documentCompleted;
wb.Navigate(url);
return tcs.Task;
}
这篇关于从 txt 文件中加载 URL 并在浏览器同步 WebClient httpRequest 中加载 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!