简体   繁体   中英

Doing POST to server from web-service

Hosted a web service that do some POST to ASPX pages.

The code:

 [WebMethod]
        public string Test()
        {
            sb.AppendLine("Start");
            try
            {
                var t = new Thread(MyThreadStartMethod);
                t.SetApartmentState(ApartmentState.STA);
                t.Start();
                t.Join();
            }
            catch (Exception ex)
            {
                sb = sb.AppendLine(ex.ToString());
            }
            sb.AppendLine("Finish");
            return sb.ToString();
        }

         private void MyThreadStartMethod(object obj)
        {
            try
            {
                WebBrowser browser = new WebBrowser();
                browser.DocumentCompleted += browser_DocumentCompleted;
                browser.Url = new Uri("http://www.wikipedia.com");
                while (browser.ReadyState != WebBrowserReadyState.Complete)
                {
                    System.Windows.Forms.Application.DoEvents();
                    Thread.Sleep(60);
                }
            }
            catch (Exception ex)
            {
                sb = sb.AppendLine(ex.ToString());
            }
        }

        void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            sb = sb.AppendLine("Document completed: " + e.Url);
        }

When trying to run it on my shared hosting server I always get timeout error.

Tried the next code to check if I can connect to third-part address and It works OK.

private bool checkUrl(string url)
{
    try
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Method = "HEAD";
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch
    {
        return false;
    }
}

Anyone can explain the problem running the first code? Do they block something?

You have to remove next 2 lines from your code

System.Windows.Forms.Application.DoEvents();
Thread.Sleep(60);

as it is stopping your webbrowser control from completing Navigate.

The best sample on how to run WebBrowser control in separate thread was proposed by Hans Passant

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM