【问题标题】:Having problems with httpost json string through vb.net通过 vb.net 遇到 httpost json 字符串问题
【发布时间】:2011-08-22 18:39:21
【问题描述】:

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

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

【问题讨论】:

  • 我收到响应“此流不支持搜索操作。”
  • 我是否以正确的方式发送 json 字符串?因为我在发送 xml 或普通字符串时使用相同的,它工作正常。从 vb.net 发送 JSON 字符串有什么不同的方法吗?
  • @slaks .. 非常感谢合并帐户。
  • HTTP 是 HTTP。 POST 正文的内容根本不重要。你的代码是正确的。 (只要nvc.ToString 返回有效的 JSON)
  • 异常的堆栈跟踪是什么?

标签: vb.net json http-post


【解决方案1】:

我认为问题在于 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

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2017-02-09
    • 2017-02-24
    相关资源
    最近更新 更多