我想检查一下用户给出的URL是否有效。因为如果不是,例如"http://www.stackoverflow",那么稍后它将使程序崩溃。我试图使用Web响应,但它找不到Irequest.GetResponse()的定义;
try
{
string url = HomepageTextBox.Text;
if (url != "")
{
WebRequest Irequest = WebRequest.Create(url);
WebResponse Iresponse = Irequest.GetResponse();
if (Iresponse != null)
{
}
}
else
{
HomepageTextBox.Text = "http://www.google.com";
}
}
catch (Exception ex)
{
MessageBox.Show("Invalid URL");
}
提前谢谢你:)
如果你需要更多的细节,请评论,我很乐意解释更多的细节:)
我记得有同样的问题,在看了MSDN网页后,我决定这是不正确的。在WP8.0中没有GetResponse(),但是在WP8.1中有GetResponseAsync()。
所以我决定使用HttpWebRequest而不是使用BeginGetResponse/EndGetResponse——据我所知,你必须使用回调。下面是一个简单的例子。
public void GetWebAddress(string web_address)
{
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(web_address);
if (request != null) request.BeginGetResponse(MyHttpCallback, request);
}
void MyHttpCallback(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
try
{
// if you're using 8.1 try enclosing theses lines with "using"
// there is no .Close()
WebResponse response = request.EndGetResponse(result);
StreamReader reader;
reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
// reponseText now contains the html/text of the page
reader.Close();
response.Close();
}
catch (WebException e)
{
// your errors are here, set your flags
string error_string = e.Message;
}
}
}