windows phone 7 - c#读取流阅读器网页Uri相对
本文关键字:网页 Uri 相对 phone 读取 windows | 更新日期: 2023-09-27 18:01:45
我下载阅读这个网页的内容,我使用这个代码这是一个Windows手机应用程序
string html = new StreamReader(Application.GetResourceStream(new Uri("http://www.knbsb.nl/nw/index.php?option=com_content&view=category&layout=blog&id=382&Itemid=150&lang=nl&LevelID=120&CompID=1580", UriKind.Relative)).Stream).ReadToEnd();
我知道UriKind是设置为相对的,但它必须为其他脚本。
所以基本上我必须使网页从一个绝对的Uri相对Uri。但我不知道该怎么做!
您需要异步发出请求。
您可以使用以下内容作为帮助器:
public static void RequestAsync(Uri url, Action<string, Exception> callback)
{
if (callback == null)
{
throw new ArgumentNullException("callback");
}
try
{
var req = WebRequest.CreateHttp(url);
AsyncCallback getTheResponse = ar =>
{
try
{
string responseString;
var request = (HttpWebRequest)ar.AsyncState;
using (var resp = (HttpWebResponse)request.EndGetResponse(ar))
{
using (var streamResponse = resp.GetResponseStream())
{
using (var streamRead = new StreamReader(streamResponse))
{
responseString = streamRead.ReadToEnd();
}
}
}
callback(responseString, null);
}
catch (Exception ex)
{
callback(null, ex);
}
};
req.BeginGetResponse(getTheResponse, req);
}
catch (Exception ex)
{
callback(null, ex);
}
}
你可以这样调用:
private void Button_Click(object sender, RoutedEventArgs e)
{
RequestAsync(
new Uri("http://www.knbsb.nl/nw/index.php?option=com_content&view=category&layout=blog&id=382&Itemid=150&lang=nl&LevelID=120&CompID=1580"),
(html, exc) =>
{
if (exc == null)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(html));
}
else
{
// handle exception appropriately
}
});
}
你可以使用WebClient来做。
using (var client = new WebClient())
{
string result = client.DownloadString("http://www.youtsite.com");
//do whatever you want with the string.
}
Application.GetResourceStream
用于从应用程序包中读取资源,而不是用于从web请求资源。
使用HttpWebRequest
或WebClient
类代替。
的例子:
string html;
using (WebClient client = new WebClient()) {
html = client.DownloadString("http://www.knbsb.nl/nw/index.php?option=com_content&view=category&layout=blog&id=382&Itemid=150&lang=nl&LevelID=120&CompID=1580");
}