2011-05-10 36 views
3

這是我用來發送郵件到指定URL的代碼。通過vb.net存在httpost json字符串的問題

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很好,我查了一下。我是否以正確的方式發送它?

+0

會發生什麼? – SLaks 2011-05-10 20:00:41

+0

我收到回覆「此流不支持查找操作。」 – lkewd 2011-05-10 20:01:40

+0

什麼是堆棧跟蹤? – SLaks 2011-05-10 20:12:34

回答

0

我相信問題是StreamReader的ReadToEnd方法在內部使用Length屬性。如果服務器不在http頭中發送長度,則這將爲空。嘗試使用內存流和緩衝區代替:

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