tags:

views:

523

answers:

4

I am just trying to perform an http post on http://www.test.com/test.asp?test1=3. Here is the code I have been trying to use:

    private void pif_test_conn()
    {


        Uri url = new Uri("http://www.test.com/test.asp?test1=3", UriKind.Absolute);



        if (httpResult == true)
        {


            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
           request.BeginGetResponse(new AsyncCallback(ReadCallback), request); 

        }



        return ;
    }


   private void ReadCallback(IAsyncResult asynchronousResult)
    {


        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;


        HttpWebResponse response =  (HttpWebResponse)request.EndGetResponse(asynchronousResult);

        using (StreamReader streamReader1 =  new StreamReader(response.GetResponseStream()))
        {

            string resultString = streamReader1.ReadToEnd();

             MessageBox.Show("Using HttpWebRequest: " + resultString, "Found", MessageBoxButton.OK);             
        }

    }

When I execute this code my program triggers the Application_UnhandledException event. Not sure what I am doing wrong.

A: 

In order to send an HTTP POST, you need to write the POST data to the request by calling the BeginGetRequestStream method.

This is probably why you're getting an exception; please tell us what exception you're geting for a more specific answer.

SLaks
System.Security.SecurityException
Weston Goodwin
+3  A: 

Are you trying to post to another host? That behavior could lead to XSS security problems, so that isnt available.


string responseValue = "";
AutoResetEvent syncRequest = new AutoResetEvent(false);
Uri address = new Uri(HtmlPage.Document.DocumentUri, "/sample.aspx");

WebRequest request = WebRequest.Create(address);
request.Method = "POST";
request.BeginGetRequestStream(getRequestResult =>
{
    // Send packet data
    using (Stream post = request.EndGetRequestStream(getRequestResult))
    {
        post.Write(buffer, 0, buffer.Length);
        post.Close();
    }

    // wait for server response
    request.BeginGetResponse(getResponseResult =>
    {
        WebResponse response = request.EndGetResponse(getResponseResult);
        responseValue=new StreamReader(response.GetResponseStream()).ReadToEnd();

        syncRequest.Set();

    }, null);

}, null);

syncRequest.WaitOne();

MessageBox.Show(
    "Using WebRequest: " + responseValue, 
    "Found", MessageBoxButton.OK);

HTH

Rubens Farias
+2  A: 

You can only send HTTP requests to the domain that your app comes from.

This restriction prevents XSS attacks.

SLaks
A: 

With regard to Rubens' answer,

If you leave in the SyncRequest.WaitOne() call, the call deadlocks, at least in Silverlight 4.0.