繁体   English   中英

通过vb.net遇到httpost json字符串问题

[英]Having problems with httpost json string through vb.net

这是我用来发送到指定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

现在问题是我在这里没有任何异常,但是我发布后应该得到的回复(成功或错误)并没有结束。 网址很好,我查了一下。 我是以正确的方式发送的吗?

我认为问题是StreamReader上的ReadToEnd方法在内部使用了Length属性。 如果服务器未在http标头中发送长度,则此值为null。 尝试使用内存流和缓冲区:

    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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM