none
HttpWebRequest - How to post multi-line data from JSON body

    Question

  • Hi, I need help.

    I'm only able to post simple text data from JSON body, and the data mustn't be multi-line.

    I need to be able to post data coming from a RichtextBox multi-line.

    I can use (Dim txtbx as String = RichTextBox1.Text) to retrieve data from RichtextBox

    Below is my code

    Imports System.Net
    Imports System.Text
    Imports System.IO
    Imports System.Diagnostics
    Imports System.IO.Compression
    
    Imports System.Net.WebUtility
    
    
    Module PostTravelForm
    
        Public logincookiePost As CookieContainer
        Dim logincookstring As String
    
        Dim theWantedString As String
    
        'Calls request functions sequentially.
        Sub MakeRequests3()
            Dim response As HttpWebResponse
            Dim responseText As String
    
            If Request_www_germany_com(response) Then
                'Success, possibly use response.
                responseText = ReadResponse(response)
    
                response.Close()
            Else
                'Failure, cannot use response.
            End If
        End Sub
    
        'Returns the text contained in the response.  For example, the page HTML.  Only handles the most common HTTP encodings.
        Public 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.travel.com/postad/create
        ''' </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_germany_com(ByRef response As HttpWebResponse) As Boolean
            response = Nothing
    
            Try
                'Create request to URL.
                Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://www.travel.com/api/postad/create"), HttpWebRequest)
                Dim tempCookies As New CookieContainer
    
                'Set request headers.
                request.KeepAlive = True
                request.Accept = "application/json, text/javascript, */*; q=0.01"
                request.Headers.Add("Origin", "https://www.travel.com")
                request.Headers.Add("x-requested-with", "XMLHttpRequest")
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
    
                request.CookieContainer = logincookiePost
    
                request.ContentType = "application/json"
                request.Referer = "https://www.travel.com/post"
                request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br")
                request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8")
    
                '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
    
                Console.WriteLine(Form3.txtbx_title.Text & " Test !!!!!!!!!!!!")
    
                Dim txtbx As String = "<p>CISCO Senior Network Engineer</p>"
    
                'Set request body.
               
                Dim body As String = "{""ads"":[{""title"":""…" + txtbx + "…"",""description"":""<p>" + Form3.txtbx_descript.Text.Replace("""", "\""") + "</p>"",""phone"":""0799654128"",""categoryId"":9250,""categoryName"":""Computer Operators"",""parentCategory"":8,""location"":{""latitude"":-33.8659683,""longitude"":18.534443499999952,""radius"":2000},""categoryAttributes"":[],""imageUrls"":[""https://i.ebayimg.com/00/s/NjAwWDgwMA==/z/~qIAAOSwU8hY75kG/$_1.PNG?set_id=8800005007""]}]}"
    
    
                Dim postBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(body)
                request.ContentLength = postBytes.Length
                Dim stream As Stream = request.GetRequestStream()
                stream.Write(postBytes, 0, postBytes.Length)
                stream.Close()
    
                '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



    • Edited by LetMeCode Monday, April 17, 2017 8:48 AM
    Sunday, April 16, 2017 4:22 PM

All replies

  • Try posting a sample text like this: “<p>Line1<br/>Line2</p>”. If it works, then send your text replacing vbCrLf with “<br/>” using Replace function.

    You can also join the lines making a text like this: “<p>Line1</p><p>Line2</p>”.


    • Edited by Viorel_MVP Sunday, April 16, 2017 6:37 PM
    Sunday, April 16, 2017 6:36 PM
  • LMC,

    This sounds similar to an issue that you'll face with XML: If you have lines in the text being written (vbCrLf), it will write the XML just fine, but... trying to parse it back in will have an issue knowing what that character is.

    With XML I've come to use a replacement character and reading it back in, I replace it back to vbCrLf.

    Unless you need to use XML or JSON, have you considered another way like binary for example? If you serialize it to binary, then deserialization understands exactly what the object originally was.

    For what it's worth...


    "A problem well stated is a problem half solved.” - Charles F. Kettering

    Sunday, April 16, 2017 10:15 PM