tags:

views:

316

answers:

3

I am looking for a built-in utility method in .NET for constructing HTTP POST message body for the two common content types:

  • application/x-www-form-urlencoded
  • multipart/form-data

I'd rather use someone else's ready and tested implementation than roll my own, even though I realise it's not difficult to do so. However there doesn't seem to be anything in System.Web to this effect.

Any suggestions?

(No need to explain how to construct the POST message body manually... that's not what this question is about)

A: 

For the application/x-www-form-urlencoded content type, simply use the UrlEncode method.

Example (in C#):

string body =
   "this=" + HttpUtility.UrlEncode(valueForThis) +
   "&" +
   "that=" + HttpUtility.UrlEncode(valueForThat) +
   "&" +
   "more=" + HttpUtility.UrlEncode(valueForMore);
Guffa
Thanks but this is what I meant by "manually". I'll do this if there's no other way.
romkyns
+1  A: 

Even easier, I like WebClient.UploadValues method. Just give it a NameValueCollection and it handles the rest:

http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadvalues.aspx

Matt Sherman
A: 
Imports System.IO
Imports System.Net

Private Function PostWebPage(ByVal argUrl As String) As String
    Dim objWebRequest As HttpWebRequest
    Dim sPostData As New StringBuilder
    Dim sr As StreamReader
    Dim objWebResponse As HttpWebResponse
    If argUrl.Length > 0 Then
        Try
            objWebRequest = CType(WebRequest.Create(argUrl), HttpWebRequest)
            objWebRequest.UserAgent = "Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+.NET+CLR+1.1.4322;+.NET+CLR+1.0.3705)"
            sPostData.Append("accountType=GOOGLE&Email=*******@gmail.com&Passwd=*******&service=analytics&source=Test")
            objWebRequest.Method = "POST"
            objWebRequest.ContentType = "application/x-www-form-urlencoded"
            objWebRequest.ContentLength = sPostData.ToString.Length
            Dim stOut As New StreamWriter(objWebRequest.GetRequestStream, System.Text.Encoding.ASCII)
            stOut.Write(sPostData)
            stOut.Close()
            objWebRequest.AllowAutoRedirect = True
            objWebRequest.Timeout = 10000
            objWebRequest.KeepAlive = True
            objWebResponse = CType(objWebRequest.GetResponse(), HttpWebResponse)
            sr = New StreamReader(objWebResponse.GetResponseStream)
            Return sr.ReadToEnd
            Exit Function
        Catch ex As Exception
        End Try
    End If
    Return ""
End Function
Mike
-1 - sorry but the question was how to construct sPostData - in your example it's just a given string.
romkyns
Try this - http://weblogs.asp.net/mikedopp/archive/2008/02/04/paypal-payflow-pro-code.aspx
Mike