TechNinjutsu‎ > ‎

Simple VB .Net Http POST to google form example

posted Jul 25, 2012, 7:47 PM by d graham   [ updated Sep 20, 2012, 6:30 PM ]
A while back(couple years if you will forgive the slightly noob-ish use of string builder and concatenation) I had need to post to a google docs from code. I downloaded the google docs sdk etc and was a bit overwhelmed at what was required considering how simple my task was(I didn't really need any of the nice features of the actual api).

I found my example on codeproject and thought I would share:

in the example I am posting a few simple fields to a form:

Imports System.Web
Imports System.Net
Imports System.IO
Imports System.Text

Public Class Form1
    Dim request As HttpWebRequest
    Dim response As HttpWebResponse = Nothing
    Dim reader As StreamReader
    Dim address As Uri
    Dim appId As String
    Dim context As String
    Dim query As String
    Dim data As StringBuilder
    Dim byteData() As Byte
    Dim postStream As Stream = Nothing
    ''Dim myHttpUtility As HttpUtility

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    End Sub

    Sub post()
        address = New Uri("http://googleform")
        ' Create the web request  
        request = DirectCast(WebRequest.Create(address), HttpWebRequest)
        ' Set type to POST  
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        ' Create the data we want to send  
        appId = "ss-form"
        data = New StringBuilder()
        data.Append("entry.0.single=" + HttpUtility.UrlEncode(BrandBox.Text))
        data.Append("&entry.2.single=" + HttpUtility.UrlEncode(ModelBox.Text))
        data.Append("&entry.3.single=" + HttpUtility.UrlEncode(ModelStringBox.Text))
        ' Create a byte array of the data we want to send  
        byteData = UTF8Encoding.UTF8.GetBytes(data.ToString())
        ' Set the content length in the request headers  
        request.ContentLength = byteData.Length
        ' Write data  
            postStream = request.GetRequestStream()
            postStream.Write(byteData, 0, byteData.Length)
            If Not postStream Is Nothing Then postStream.Close()
        End Try
            ' Get response  
            response = DirectCast(request.GetResponse(), HttpWebResponse)
            ' Get the response stream into a reader  
            reader = New StreamReader(response.GetResponseStream())
            ' Console application output  
            If Not response Is Nothing Then response.Close()
        End Try


    End Sub

End Class

This fairly simple bit of code was the end result of the Wireshark analysis of the actual google form posting discussed here.

The basic idea is that by using wireshark to take a peek at the actual "POST" request submitted by a google generated form, you can extrapolate the bits necessary for your own "POST".