2014-02-06 50 views
1

我的網絡請求後,我的網站響應內容長度總是似乎爲-1。我相信你的按摩和簽名是正確的。 我在這裏做錯了什麼?HttpWebResponse contentLength始終爲-1

  string msg = string.Format("{0}{1}{2}", nonce, clientId, apiKey); 
      string signature = ByteArrayToString(SignHMACSHA256(apiSecret, StrinToByteArray(msg))).ToUpper(); 
      const string endpoint = "https://www.bitstamp.net/api/balance/"; 
      HttpWebRequest request = WebRequest.Create(endpoint) as HttpWebRequest; 
      request.Proxy = null; 
      request.Method = "POST"; 
      request.ContentType = "application/xml"; 
      request.Accept = "application/xml"; 
      request.Headers.Add("key", apiKey); 
      request.Headers.Add("signature", signature); 
      request.Headers.Add("nonce", nonce.ToString()); 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 

回答

1

知道它使用webClient而不是httpWebRequest。 如果有人可以使用httpWebRequest來處理它,你會得到答案。

  string msg = string.Format("{0}{1}{2}", nonce, clientId, apiKey); 
      var signature = ByteArrayToString(SignHMACSHA256(apiSecret, StrinToByteArray(msg))).ToUpper(); 
      var path = "https://www.bitstamp.net/api/user_transactions/"; 

      using (WebClient client = new WebClient()) 
      { 

       byte[] response = client.UploadValues(path, new NameValueCollection() 
       { 
        { "key", apiKey }, 
        { "signature", signature }, 
        { "nonce", nonce.ToString()}, 

       }); 

       var str = System.Text.Encoding.Default.GetString(response); 
      } 
+0

這可以工作,因爲您不檢查Content-Length標頭。如果爲流創建StreamReader並將流讀到最後,您也可以使用HttpWebRequest進行此項工作。 –

2

the documentation

的的ContentLength屬性包含與響應中返回的的ContentLength標頭的值。如果Content-Length報頭未在響應中設置,則ContentLength設置爲值-1。

+0

確實如此,但這通常由服務器負責,因此大多數看到此情況的人都對這個原因感興趣。對於大多數人來說,我在下面描述的原因是 - 返回正在流式傳輸或分塊。 –

0

因爲這與「Web客戶端」的工作,沒有什麼不對的請求,這意味着幾乎可以肯定的是,請求被髮送回「分塊」。這由標題'Transfer-Encoding'表示。

Web服務器可能發回一些分塊的原因有幾個原因,包括返回是二進制的。

我來到這個頁面是因爲Fiddler通過服務器轉向一個非常好的響應來「干擾」我的請求,然後將它返回給我的客戶端。那是因爲我有'流'按鈕被按下或活動。如果不是,則它將數據發送回緩衝區,以保留服務器的響應。這是一個可怕的事情追查..

但研究確實告訴我爲什麼內容長度標題可能是-1。

解決方案?要麼修復服務器(或我的代理)發送響應的方式,要麼只是將響應流讀到最後。後者會將所有塊返回給您連接,並且您可以獲取返回的字節長度。

Stream responseStream = response.GetResponseStream(); 
StreamReader reader = new StreamReader(responseStream); 
String responseString = reader.ReadToEnd(); 
int responseLength = responseString.Length; 

如果你想字節是更復雜 - 不知道是否有一個閱讀器,可以讀取到最後 - 二進制讀者需要一個緩衝了前面。

An elegant way to consume (all bytes of a) BinaryReader?

恩喬伊。