1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

HttpWebRequest / How to upload picture before posting

Discussion in 'Visual Basic .NET' started by Free6, Jan 16, 2017.

  1. Free6

    Free6 Newbie

    Joined:
    Nov 21, 2016
    Messages:
    31
    Likes Received:
    0
    Gender:
    Female
    Hi, I'm trying to make a HttpWebRequest and I have to attach/upload a picture before I submit the form.

    Below is the code that contain my picture's name.

    There's a variable called "u" in the code below that contains the name of the picture I uploaded called "Penguins.jpg",

    I tried to remove the "Penguins.jpg" and put a static link like "c:\mypictures.jpg" in the body string below, but didn't work.

    Need I upload the picture first to their Server? If so, how do I know the new name of my picture then???

    Please can you help?

    Code:
    Dim body As String = "locationId=3100529&categoryId=9227&machineId=8082c5b9-fde3-443a-97a8-dd82680fb01c-15992400abb&completenessPercentage=64&munchkinId=038-AZF-323&_mrk_trk=&ForSaleBy=&Title=Addidas+Presto+for+Sale&Description=Addidas+Presto+for+sale.%3Cdiv%3E%3Cbr%3E%3C%2Fdiv%3E%3Cdiv%3EOpen+to+Neg.%3C%2Fdiv%3E%3Cdiv%3E%3Cbr%3E%3C%2Fdiv%3E%3Cdiv%3EContact+me+for+Price%3C%2Fdiv%3E&WebSiteUrl=&u=Penguins.jpg&profilePicture=&picturesThumb=https%253A%252F%252Fi.ebayimg.com%252F00%252Fs%252FNjAwWDgwMA%253D%253D%252Fz%252FduoAAOSw-0xYd1ze%252F%2524_14.JPG&pictures=https%253A%252F%252Fi.ebayimg.com%252F00%252Fs%252FNjAwWDgwMA%253D%253D%252Fz%252FduoAAOSw-0xYd1ze%252F%2524_18.JPG&priceTypes=FIXED&Price=&currencyValues=ZAR&UserName=Orange&Email=myemail145%40gmail.com&Phone=123456789&latitude=&longitude=&adminAreaName=&addressConfidenceLevel=&countryCode=&street=&locality=&Address="
     
  2. gimme4free

    gimme4free Executive VIP Jr. VIP Premium Member

    Joined:
    Oct 22, 2008
    Messages:
    1,925
    Likes Received:
    1,942
    Home Page:
    You should record the headers of the entire process & then replicate necessary calls. At some point their will be an image upload that wil return a URL of where the image is now hosted that you can add to your post data for the second call.
     
  3. Free6

    Free6 Newbie

    Joined:
    Nov 21, 2016
    Messages:
    31
    Likes Received:
    0
    Gender:
    Female
    Thanks.
    Below is the code for Picture uploading recorded via Fiddler but I can't find where to put my variable in order to make it dynamic.

    Please can you help ?

    Code:
    
    'Calls request functions sequentially.
    Private Sub MakeRequests()
        Dim response As HttpWebResponse
        Dim responseText As String
    
        If Request_www_gumtree_co_za(response) Then
            'Success, possibly use response.
            responseText = ReadResponse(response)
    
            response.Close()
        Else
            'Failure, cannot use response.
        End If
    End Sub
    
    'Parses and writes the multipart body to the web request.
    Private Shared Sub WriteMultipartBodyToRequest(ByRef request As HttpWebRequest, ByRef body As String)
        Dim multiparts As String() = Regex.Split(body, "<!>")
        Dim bytes As Byte()
        Using ms As New MemoryStream()
            For Each part As String In multiparts
                ' Determine if part is plain text or "<!>" line.
                If File.Exists(part) Then
                    bytes = File.ReadAllBytes(part)
                Else
                    bytes = System.Text.Encoding.UTF8.GetBytes(part.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n"))
                End If
    
                ms.Write(bytes, 0, bytes.Length)
            Next
    
            request.ContentLength = ms.Length
            Using stream As Stream = request.GetRequestStream()
                ms.WriteTo(stream)
            End Using
        End Using
    End Sub
    
    'Returns the text contained in the response.  For example, the page HTML.  Only handles the most common HTTP encodings.
    Private Shared Function ReadResponse(response As HttpWebResponse) As String
        Using responseStream = response.GetResponseStream()
            Dim streamToRead As Stream = responseStream
            If response.ContentEncoding.ToLower().Contains("gzip") Then
                streamToRead = New GZipStream(streamToRead, CompressionMode.Decompress)
            ElseIf response.ContentEncoding.ToLower().Contains("deflate") Then
                streamToRead = New DeflateStream(streamToRead, CompressionMode.Decompress)
            End If
    
            Using streamReader = New StreamReader(streamToRead, Encoding.UTF8)
                Return streamReader.ReadToEnd()
            End Using
        End Using
    End Function
    
    ''' <summary>
    ''' Tries to request the URL: https://www.gumtree.co.za/image/upload
    ''' </summary>
    ''' <param name="response">After the function has finished, will possibly contain the response to the request.</param>
    ''' <returns>True if the request was successful; false otherwise.</returns>
    Private Function Request_www_gumtree_co_za(ByRef response As HttpWebResponse) As Boolean
        response = Nothing
    
        Try
            'Create request to URL.
            Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.gumtree.co.za/image/upload"), HttpWebRequest)
    
            'Set request headers.
            request.KeepAlive = True
            request.Headers.Add("Origin", "https://www.gumtree.co.za")
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
            request.ContentType = "multipart/form-data; boundary=----WebKitFormBoundarynoaM3PHquZSAbvAt"
            request.Accept = "*/*"
            request.Referer = "https://www.gumtree.co.za/post.html"
            request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br")
            request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8")
            request.Headers.Set(HttpRequestHeader.Cookie, "anonUsrId=cixzt744c3l4d2aauebrgfhil; __gads=ID=c6013512bb7373fa:T=1484554131:S=ALNI_MZRpw0rjCLTKstKJunP2q1pRIyHOQ; _em_d=1484554994; _gat=1; __utmt_siteTracker=1; testCookie=true; rememberMe=ZnJlZXNpeDAwN0BnbWFpbC5jb206MTQ4NzE3MzUxMTgyMTowZTYyYjI4M2M2OTcxNDI3ZWY0ZTdkY2VmZTZiMGNhNA; _ga=GA1.3.1116734716.1484554219; __utma=29192163.1116734716.1484554219.1484554219.1484581576.2; __utmb=29192163.5.10.1484581576; __utmc=29192163; __utmz=29192163.1484554219.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _mkto_trk=id:038-AZF-323&token:_mch-gumtree.co.za-1484554223384-20010; _em_t=true; _em_vt=aa8911ca58c7eb33324192e76327587c7ec7bf9674-86337398587ceaa7; _em_v=949c0cbd9ef409e1e937a15940ad587cea705b2899-59378804587ceaa7; prevRedirect=/; machguid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264785; optimizelySegments=%7B%221023101167%22%3A%22false%22%2C%221031302104%22%3A%22gc%22%2C%221034051149%22%3A%22direct%22%2C%222187250012%22%3A%22none%22%7D; optimizelyBuckets=%7B%7D; optimizelyPendingLogEvents=%5B%5D; _gali=pictures")
    
            'Set request method
            request.Method = "POST"
    
            ' Disable 'Expect: 100-continue' behavior. More info: http://haacked.com/archive/2004/05/15/http-web-request-expect-100-continue.aspx
            request.ServicePoint.Expect100Continue = False
    
            'Set request body.
            Dim body As String = "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""s""" & vbCrLf & _
    "" & vbCrLf & _
    "Standard" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""axrequest""" & vbCrLf & _
    "" & vbCrLf & _
    "2" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""xmlhttp2""" & vbCrLf & _
    "" & vbCrLf & _
    "true" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""v""" & vbCrLf & _
    "" & vbCrLf & _
    "2" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""b""" & vbCrLf & _
    "" & vbCrLf & _
    "18" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""n""" & vbCrLf & _
    "" & vbCrLf & _
    "g" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""a""" & vbCrLf & _
    "" & vbCrLf & _
    "AgAAAA**AQAAAA**aAAAAA**yeFbVA**nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wFk4GhCJGLpAydj6x9nY+seQ**X60BAA**AAMAAA**N7T4wsT9Ju+MfgG2V/6QpTHVbPJ9PDG6nNDMyS0hoWLI+4mi4xCKmSmhHvqn1tomMK2On4AHgsg6tk8zB0kUlUtaMEvySDyNJDi9IFw7tsOiy+Jmh9yrZXSiQ0DvYbr37XRGT3upJo7RcpKW9tUDiIkrpI4N6oZNV0UaL8DZxMXQFQIooedrao0vtDmLMZkaqhl9/EhpmnfSszT2UA5LkYeSihU2x6j1Wg45+iRNVV0+oFoPgI3nK50WxIyBBVd2rWaBW0rm76rEdL6J9MFwVhQ3/HPfSjeTjtytzzUIcVyBUKF9jk1gj/1JXdXhy23iXWO2XbWR9SJg7xedyDXktpp5e+JZIjTUmvEH9DTW9gmONwmDzAD7t40xuCAc5b56I35aa5kM7s+sUR7TjvsGkmG9l8w1MDZfko8RxTXDiUN1Kg0zUp2lmvHHTkv0keSmxexs8JTY9pjLVd8m0e3xURAqfIMGdYJnj+mcJek5ZQZUgOgPG6Mor+j7XHqf2SIW6mOlvHOL3F4nST2QEDRdgnCAEeS3G5V/CiiQizOX2TWBJ3q6huo5EaN5x8RR6giCMWfbdrnbfPDz6lboR680sBZVgOqSoI5HcjohTXB2QsfD7kUqy3GImaK4SchEZ7JHyaAw51wkp8pMVmtN5hZhgzbiyQkefkpVYiA64Bz0MwQuK6QgIXhm5JW+zUY84mXOrXNrAP2fDglT8SCc7pm1zNj2E61OT17b9+Mm8DU3WLcaAAkMKG1FnkGZZcmD0Lfn" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""file""; filename=""blob""" & vbCrLf & _
    "Content-Type: image/png" & vbCrLf & _
    "" & vbCrLf & _
    "<!>C:\\Users\\Francis\\AppData\\Local\\Temp\\iy2n3bal\\blob<!>" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""rqt""" & vbCrLf & _
    "" & vbCrLf & _
    "1484581663620" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt" & vbCrLf & _
    "Content-Disposition: form-data; name=""rqis""" & vbCrLf & _
    "" & vbCrLf & _
    "11791" & vbCrLf & _
    "------WebKitFormBoundarynoaM3PHquZSAbvAt--" & vbCrLf & _
    ""
            WriteMultipartBodyToRequest(request, body)
    
            'Get response to request.
            response = DirectCast(request.GetResponse(), HttpWebResponse)
        Catch e As WebException
            'ProtocolError indicates a valid HTTP response, but with a non-200 status code (e.g. 304 Not Modified, 404 Not Found)
            If e.Status = WebExceptionStatus.ProtocolError Then
                response = DirectCast(e.Response, HttpWebResponse)
            Else
                Return False
            End If
        Catch e As Exception
            If response IsNot Nothing Then
                response.Close()
            End If
            Return False
        End Try
    
        Return True
    End Function