views:

571

answers:

2

I have been using the following code to obtain a simple web response from Apache 2.2 in SilverLight to no avail.

    private void bDoIt_Click(object sender, RoutedEventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("/silverlight/TestPage2.html"));

        request.Method = "POST";
        request.ContentType = "text/xml";

        request.BeginGetRequestStream(new AsyncCallback(RequestProceed), request);
    }

    private void RequestProceed(IAsyncResult asuncResult)
    {
        HttpWebRequest request = (HttpWebRequest)asuncResult.AsyncState;

        StreamWriter postDataWriter = new StreamWriter(request.EndGetRequestStream(asuncResult));
        postDataWriter.Close();

        request.BeginGetResponse(new AsyncCallback(ResponceProceed), request);

    }

    private void ResponceProceed(IAsyncResult asuncResult)
    {
        HttpWebRequest request = (HttpWebRequest)asuncResult.AsyncState;

        HttpWebResponse responce = (HttpWebResponse)request.EndGetResponse(asuncResult);
        StreamReader responceReader = new StreamReader(responce.GetResponseStream());

        string responceString = responceReader.ReadToEnd();

        txtData.Text = responceString;
    }

Does anyone no a better method of doing this?

+1  A: 

Have you tried WebClient? This exists on silverlight, and might make life easier. Presumably you'd want UploadStringAsync.

Also - I believe you need to use and absolute url; if you don't want to hard code (quite reasonably), you can get your host from:

string url = App.Current.Host.Source.AbsoluteUri;

Then use string / etc methods to make the correct "http://yoursite/whatever/your.page";

Note that silverlight only allows (IIRC) connections to the host site.

Marc Gravell
Thank you, that worked brilliantly
williamtroup
A: 

You can do the BeginGetResponse call as the first call in your sample test case, the BeginGetRequestStream call is only needed if you are intending to pass some POST data to the requested page.

tucod