通过 vb.net 使用 httpost json 字符串时遇到问题
这是我用来以帖子形式发送到指定 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
现在的问题是我在这里没有得到任何异常,但是我应该在发布后得到的响应(成功或错误)并没有结束。网址没问题,我查了一下。我发送的方式正确吗?
Here's my code that I am using to send as post 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 I don't get any exception here, but the response I'm supposed to get after posting (success or error) is not coming to my end. The URL is fine, I checked it. Am I sending it the right way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题在于 StreamReader 上的 ReadToEnd 方法内部使用 Length 属性。如果服务器未在 http 标头中发送长度,则该值为 null。尝试使用内存流和缓冲区:
I believe the issue is that ReadToEnd method on StreamReader internally uses the Length property. This will be null if the server doesn't send a length in the http header. Try using memory stream and a buffer instead: