Problems with httpost json string via vb.net

Here is my code that I use to send a message to the specified URL.

Dim url = "http://www.abc.com/new/process"

Dim data As String = nvc.ToString
Dim postAddress = New Uri(Url)

Dim request = DirectCast(WebRequest.Create(postAddress), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/json"
Dim postByteData As Byte() = UTF8Encoding.UTF8.GetBytes(data)
request.ContentLength = postByteData.Length

Using postStream As Stream = request.GetRequestStream()
    postStream.Write(postByteData, 0, postByteData.Length)
End Using

Using resp = TryCast(request.GetResponse(), HttpWebResponse)
    Dim reader = New StreamReader(resp.GetResponseStream())
    result.Response = reader.ReadToEnd()
End Using

Now the problem is that here I am not getting any exception, but the answer I should get after posting (success or error) does not suit me. The url is ok, I checked it. Am I sending it right?

+3
source share
1 answer

I believe the problem is that the ReadToEnd method on StreamReader internally uses the Length property. This will be null if the server does not send the length in the http header. Instead, try using a memory stream and a buffer:

    Dim url = "http://my.posturl.com"

    Dim data As String = nvc.ToString()
    Dim postAddress = New Uri(url)

    Dim request As HttpWebRequest = WebRequest.Create(postAddress)
    request.Method = "POST"
    request.ContentType = "application/json"
    Dim postByteData As Byte() = UTF8Encoding.UTF8.GetBytes(data)
    request.ContentLength = postByteData.Length

    Using postStream As Stream = request.GetRequestStream()
        postStream.Write(postByteData, 0, postByteData.Length)
    End Using

    Using resp = TryCast(request.GetResponse(), HttpWebResponse)
        Dim b As Byte() = Nothing
        Using stream As Stream = resp.GetResponseStream()
            Using ms As New MemoryStream()
                Dim count As Integer = 0
                Do
                    Dim buf As Byte() = New Byte(1023) {}
                    count = stream.Read(buf, 0, 1024)
                    ms.Write(buf, 0, count)
                Loop While stream.CanRead AndAlso count > 0
                b = ms.ToArray()
            End Using
        End Using
        Console.WriteLine("Response: " + Encoding.UTF8.GetString(b))
        Console.ReadLine()
    End Using
0
source

All Articles