How to send data with POST methods from C# code
Last post 04-08-2008 3:18 PM by parimaln. 5 replies.
Sort Posts:
03-31-2008 5:09 AM
How to send data with POST methods from C# code

Hi,

 I need to send data to the MySQL database. I was thinking in making POSTs in order to receive them by php and then inserted the data into the database.

What do you people think about this approach? How can i do such POST requests from C#? Is there any other way of doing this?

Thx,

Nuno
 

--

Imagining the future

(If this has answered your question, please click on "Mark as Answer" on this post. Thank you!)

sinosoidal

Joined on 01-07-2008
Braga, Portugal
Posts 176
03-31-2008 5:48 AM
Marked as Answer
Re: How to send data with POST methods from C# code

sinosoidal:
How can i do such POST requests from C#?
 

You can use either HttpWebRequest or XmlHttpRequest Wrapper.

The following code is for HttpWebRequest.

private void InvokeAsync() {

            //http://msdn2.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx

            string serviceURL = "http://localhost:52976/YourServices.php";


            pMessage = "ProductName=\"jetli\"";


            // Create a new HttpWebRequest object.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceURL);


            // Set the Method property to 'POST' to post data to the URI.
            request.Method = "POST";
            // Start the asynchronous operation.  
            request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);

            // Keep the main thread from continuing while the asynchronous
            // operation completes. A real world application
            // could do something useful such as updating its user interface.
            allDone.WaitOne();

            // Get the response.
            request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
          
        }
        private static void ResponseCallback(IAsyncResult asynchronousResult) {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse resp = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            Stream streamResponse = resp.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            string responseString = streamRead.ReadToEnd();
            Console.WriteLine(responseString);
            // Close the stream object.
            streamResponse.Close();
            streamRead.Close();

            // Release the HttpWebResponse.
            resp.Close();
        }
        private static void ReadCallback(IAsyncResult asynchronousResult) {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            // End the operation.
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

            string postData = pMessage;

            // Convert the string into a byte array.
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Write to the request stream.
            postStream.Write(byteArray, 0, postData.Length);
            postStream.Close();
            allDone.Set();
        }

 

You can also read this post. http://www.talentgrouplabs.com/blog/archive/2008/03/11/asynchronous-http-post-request-with-silverlight-2.0-beta-1.aspx 

 

 

(If this has answered your question, please click on "Mark as Answer" on this post. Thank you!)

Best Regards,
Michael Sync

Blog : http://michaelsync.net
Feed : http://michaelsync.net/feed

mchlSync

Joined on 09-16-2005
Singapore
Posts 2,021
04-08-2008 3:11 AM
Re: How to send data with POST methods from C# code

Hi,

I followed all the steps that is mentioned in the link given by you.

When i try to access the aspx page added in the Hosting Web Project of SL Prohect, i am ble to get the data read in the aspx page from DB. But when i try to access the same aspx page hosted on web server i fail to get the result and get Null error at following line

StreamReader reader = new StreamReader(response.GetResponseStream());

Need help on urgent basis.

Parimal

 

Code

private void Button1_Click(object sender, RoutedEventArgs e)

{

string uri = "http://<<webserver name>>/ArchitectFeed/RSS2.0.aspx";

Uri serviceURL = new Uri(uri);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceURL);

request.Method = "Post";

request.ContentType = "text/XML";request.BeginGetRequestStream(new AsyncCallback(RequestProcedd), request);

}

private void RequestProcedd(IAsyncResult asyncResult)

{

HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

StreamWriter poststreamwrite = new StreamWriter(request.EndGetRequestStream(asyncResult));poststreamwrite.WriteLine("<skillsMatrix role='Solution Architect'><category name='Fundamentals'><skill name='Outsourcing' currentlevel='1' rolelevel='3' /></category></skillsMatrix>");

poststreamwrite.Close();

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

}

private void ResponseProceed(IAsyncResult ayncresult)

{

try

{

HttpWebRequest request = (HttpWebRequest)ayncresult.AsyncState;

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

StreamReader reader = new StreamReader(response.GetResponseStream());

StringBuilder strb = new StringBuilder();

while (reader.Peek() >= 0)

{

//Response.Write((char)_Answer.Read());

strb.Append((char)reader.Read());

}

xlog.Text = strb.ToString();

}

catch (Exception ex)

{

}

parimaln

Joined on 01-24-2008
Posts 84
04-08-2008 3:28 AM
Re: How to send data with POST methods from C# code

The URL of your website and the url of your service are different?  IF yes, you will need to configure the cross-domain policy in your service.

(If this has answered your question, please click on "Mark as Answer" on this post. Thank you!)

Best Regards,
Michael Sync

Blog : http://michaelsync.net
Feed : http://michaelsync.net/feed

mchlSync

Joined on 09-16-2005
Singapore
Posts 2,021
04-08-2008 3:38 AM
Re: How to send data with POST methods from C# code

Hi,

Thanks for the response.

I will create the crossdomain.xml as shown below

<?xml version="1.0" ?>

  <!DOCTYPE cross-domain-policy (View Source for full doctype...)>
- <cross-domain-policy>
  <allow-access-from domain="*" secure="false" />
  </cross-domain-policy>
 
What are the steps for putting this on the webserver and what other settings i need to do?
Thanks
Parimal
parimaln

Joined on 01-24-2008
Posts 84
04-08-2008 3:18 PM
Re: How to send data with POST methods from C# code

Hi,

I resolved the issue by placing the CrossAccessPolicy.xml file at my IIS root folder where my service is running:

E:\Intepub\wwwroot

clientaccesspolicy.xml

<?xml version="1.0" encoding="utf-8"?>
<access-policy>

<cross-domain-access>
<policy>

<allow-from>
<domain uri="*"/>

</allow-from>
<grant-to>

<resource path="/" include-subpaths="true"/>
</grant-to>

</policy>
</cross-domain-access>

</access-policy>

regards,

Parimal

parimaln

Joined on 01-24-2008
Posts 84