通过vb.net使用httpost json字符串时出现问题
这是我的代码,我正在使用它作为post发送到指定的URL通过vb.net使用httpost json字符串时出现问题,vb.net,json,http-post,Vb.net,Json,Http Post,这是我的代码,我正在使用它作为post发送到指定的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.Conten
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
现在的问题是我在这里没有得到任何例外,但我应该在发布后得到的回复(成功或错误)并没有结束。URL很好,我检查过了。我发送的方式正确吗?我认为问题在于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
我得到的响应是“此流不支持seek操作”。我是否以正确的方式发送json字符串?因为我在发送xml或普通字符串时使用了相同的方法,而且效果很好。是否有其他方法从vb.net发送JSON字符串?@slaks。。非常感谢您合并帐户。HTTP就是HTTP。帖子正文的内容根本不重要。你的代码是正确的。(只要
nvc.ToString
返回有效的JSON)异常的堆栈跟踪是什么?