views:

335

answers:

4

I am using HTTPWebRequest to post data to a webserver in Silver light 3.0, here is my code

    public void MakePostRequest()
    {


            // Create a new HttpWebRequest object.

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.mywebsite.com/somepage.php");    

            // Set the ContentType property. 
            request.ContentType="application/x-www-form-urlencoded";
            // 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)
    {    
            IDictionary<string, string> objDictionary = new Dictionary<string, string>();  
            objDictionary.Add("action", "login");
            objDictionary.Add("login", "[email protected]");
            objDictionary.Add("password", "pass123");


            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            // End the operation.
            // This line of code making the blocking call???
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

            Stream memStream = new System.IO.MemoryStream();

            byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");

            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            foreach (KeyValuePair<string, string> entry in objDictionary)
            {
                string key = entry.Key;
               string value = entry.Value;
                string formitem = string.Format(formdataTemplate, key, value);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }

        memStream.Write(boundarybytes, 0, boundarybytes.Length);



        memStream.Position = 0;
        byte[] tempBuffer = new byte[memStream.Length];
        memStream.Read(tempBuffer, 0, tempBuffer.Length);

        //Writing the name value pair
        postStream.Write(tempBuffer, 0, tempBuffer.Length);

        memStream.Close();
        postStream.Close();

}

The problem I am facing is that the line Stream postStream = request.EndGetRequestStream(asynchronousResult); is making some blocking call, and whole of my application seems to be hanged.. however I can open the same webpage from the browser... Why it is so?

A: 

It seems that this isn't all of your code since there is this:

 allDone.WaitOne();

That would be the source of your blocking call most likely.

Bryant
+2  A: 

Remove your use of the Wait handle allDone. Instead move your call to BeginGetResponse to the end of the ReadCallback method. In effect you chain the calls:-

BeginGetRequest->ReadCallback->BeginGetResponse->ResponseCallback

BTW, You are using a Content-Type of "application/x-www-form-urlencoded". However you appear to be attempting to encode a Multipart entity body in which case your content type should be "multipart/form-data".

AnthonyWJones
A: 

If all you want to do is POST and name/value pair collection to the server, just use WebClient. In two lines of code you can achieve what you want.

Of course, it wont give you fine grained control, like being able to implement async, but in the end, it will get the job done.

feroze
will you please let me know the two lines of code for posting data to URL in Silverlight?
Ummar
A: 

seems or might be, you are going to get access to an URL that need 'permission'. The Web browser store 'cookie' or any to reside your access permission, but your application are not. Once you get login to that URL using browser, you get that access permission only for your browser application, and cannot derived to another application.

yudha ph