Search code examples
silverlightsilverlight-3.0http-post

Adding data to a silverlight HTTP POST Async


I'm trying to send some data using a simple HTTP POST in Silverlight 3.0 but for some reason I can't seem to find a good example on how to do this.

So far this works, but how do I send some data along w/ the request?

Public Sub SubmitMessage()
    request = WebRequestCreator.ClientHttp.Create(New System.Uri("http://localhost:27856/Home.aspx/PostUpdate/"))
    request.Method = "POST"

    Dim result As IAsyncResult = request.BeginGetResponse(New AsyncCallback(AddressOf UpdateDone), Nothing)
End Sub

Public Sub UpdateDone(ByVal ar As IAsyncResult)
    Dim response As HttpWebResponse = request.EndGetResponse(ar)

    Using reader As StreamReader = New StreamReader(response.GetResponseStream())
        Dim valid As String = reader.ReadToEnd()
    End Using
End Sub

Solution

  • You need the BeginGetRequestStream method before getting the response (note VB.NET is not my main language).

    Public Sub SubmitMessage()
        request = WebRequestCreator.ClientHttp.Create(New System.Uri("http://localhost:27856/Home.aspx/PostUpdate/"))
        request.Method = "POST"
    
        request.BeginGetRequestStream(New AsyncCallback(AddressOf SendData), Nothing)
    End Sub
    
    Public Sub SendData(ByVal ar As IAsyncResult)
        Dim stream as Stream = state.Request.EndGetRequestStream(ar)
        '' # Pump your data as bytes into the stream.
        stream.Close()
        request.BeingGetResponse(New AsyncCallback(AddressOf UpdateDone), Nothing)
    End Sub
    
    Public Sub UpdateDone(ByVal ar As IAsyncResult)
        Dim response As HttpWebResponse = request.EndGetResponse(ar)
    
        Using reader As StreamReader = New StreamReader(response.GetResponseStream())
            Dim valid As String = reader.ReadToEnd()
        End Using
    End Sub
    

    It would seem from your answer that the are posting HTML form data. Here is the correct way to create the entity body (C# sorry):-

        public static string GetUrlEncodedData(Dictionary<string, string> data)
        {
            var sb = new StringBuilder();
            foreach (var kvp in data)
            {
                if (sb.Length > 0) sb.Append("&");
                sb.Append(kvp.Key);
                sb.Append("=");
                sb.Append(Uri.EscapeDataString(kvp.Value));
            }
            return sb.ToString();
        }
    

    Note in particular the use of Uri.EscapeDataString, this the correct way to encode data values for this Content-Type. It assumes that the server is expecting UTF-8 character encoding.

    When converting the result of this to a byte array ready for posting you need only use ASCII encoding since the returned string will only ever contain characters within the ASCII range.