自定义类中的HttpWebRequest

时间:2012-05-12 23:08:16

标签: windows-phone-7 c#-4.0 httpwebrequest

我试图为windows phone 7芒果制作应用,以解析网站的内容。我设法编写了所有代码,但它就像一个战区;)。当我试图以更好的方式重新排列代码时,我开始面临一个非常奇怪的问题。

问题在于我制作了一个名为" MedinetMySchedule"在我的项目中并使用断点来逐步完成这个类。我发现应用程序逐步执行第一个方法getrequest()然后返回主页几步,然后返回第二个方法GetRequestStreamCallback()。这个跳转到主页给我留下了一个值为null的字符串来解析。然后它跳回到第三个方法ReadWebRequestCallback()。最后一次跳转没有给我任何重要的调试结束,我在手机模拟器上什么也得不到。 MedinetMySchedule类具有以下代码: -

namespace WindowsPhonePanoramaApplication1
{
    public class MedinetMySchedule
    {

        //Medinet user url
        public string url { get; set; }
        public String myresponse;
        public void getrequest()
        {
            HttpWebRequest request = HttpWebRequest.CreateHttp(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.BeginGetRequestStream(GetRequestStreamCallback, request);
        } 

        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            using (Stream postStream = request.EndGetRequestStream(asynchronousResult))
            {
                string postData = string.Format("username={0}&password={1}&customer=******&doLogin=Logga+in&language=se", "*****", "******");

                // Convert the string into a byte array.
                byte[] data = Encoding.UTF8.GetBytes(postData);


                // Write to the request stream.
                postStream.Write(data, 0, data.Length);
                postStream.Close();
            }

            //Initiating get response
            request.BeginGetResponse(ReadWebRequestCallBack, request);

        }

        private void ReadWebRequestCallBack(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            WebResponse myResponse = (WebResponse)request.EndGetResponse(asynchronousResult);
                Stream encodingStream = myResponse.GetResponseStream();
                Encoding encode = Encoding.GetEncoding("iso-8859-1");
                using (StreamReader httpwebStreamReader = new StreamReader(encodingStream, encode))
                {
                    myresponse= httpwebStreamReader.ReadToEnd();
                }
                myResponse.Close();
        }
    }
 }

以下是调用getrequest()并解析内容的代码: -

            MedinetMySchedule mittschema = new MedinetMySchedule();
        mittschema.url = "https://medinet.se/cgi-bin/doctor.pl?action=login&customer=saskir&language=se";
        mittschema.getrequest();
        Dispatcher.BeginInvoke(() => parseResults(mittschema.myresponse));
        private void parseResults(string myresponse)
    {
        if (string.IsNullOrEmpty(myresponse))
        {
            return;
        }

        //Initiating a listbox and add item to it
        List<MediNetScheme> medinetScheme = new List<MediNetScheme>();
        //Using HtmlAgilityPack to parse the HTMLcode from the response
        HtmlDocument htdoc = new HtmlDocument();
        htdoc.LoadHtml(myresponse);
        foreach (HtmlNode table in htdoc.DocumentNode.SelectNodes("//table[@class='list-medium']/tbody[1]/tr[@class]"))
        {
            //Removing ChildNode
            table.ChildNodes.RemoveAt(3);
            string itemValue = table.InnerText;
            //Changing the parsed date into a DateTime
            string d;
            DateTime datum = DateTime.Parse(itemValue.Remove(11));
            d = datum.ToString("D");
            //Adding items to the listbox
            medinetScheme.Add(new MediNetScheme() { Datum = d, Sections = itemValue.Remove(0, 15) });
        }
        MediNetScheme.ItemsSource = medinetScheme;

    }

为什么会发生这种情况以及如何纠正它?

此致 /奥马

1 个答案:

答案 0 :(得分:2)

执行来回是因为request.BeginGetRequestStream是异步的。基本上,它创建一个新线程,并与主代码并行执行。因此,在完成数据下载之前,最终会调用parseResult。有很多方法可以重写代码,我最喜欢的是使用回调:

首先,更改getRequest方法以接受回调,并将其存储:

    private Action Callback;

    public void getrequest(Action callback)
    {
        this.Callback = callback;
        HttpWebRequest request = HttpWebRequest.CreateHttp(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.BeginGetRequestStream(GetRequestStreamCallback, request);
    } 

然后,在ReadWebRequestCallback结束时,调用此回调:

    private void ReadWebRequestCallBack(IAsyncResult asynchronousResult)
    {
        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
        WebResponse myResponse = (WebResponse)request.EndGetResponse(asynchronousResult);
            Stream encodingStream = myResponse.GetResponseStream();
            Encoding encode = Encoding.GetEncoding("iso-8859-1");
            using (StreamReader httpwebStreamReader = new StreamReader(encodingStream, encode))
            {
                myresponse= httpwebStreamReader.ReadToEnd();
            }
            myResponse.Close();

        this.Callback();
    }

最后,从主页调用getrequest方法并告诉它使用parseResults作为回调:

Action callback = () => Dispatcher.BeginInvoke(() => parseResults(mittschema.myresponse));
mittschema.getrequest(callback);