2016-04-25 64 views
0

我試圖使用.net將數據點放在OpenTSDB中,使用HTTP/api/put API。 我試過用httpclient,webRequest和HttpWebRequest。結果總是400 - 錯誤請求:分塊請求不受支持。在.NET中使用OpenTSDB HTTP API:400錯誤請求

我試過我的有效載荷與api測試儀(DHC)和工作得很好。 我試着發送一個非常小的有效負載(即使明顯錯誤,如「x」),但答覆總是相同的。

這裏是我的代碼實例之一:

public async static Task PutAsync(DataPoint dataPoint) 
    { 
     try 
     { 
      HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:4242/api/put"); 
      http.SendChunked = false; 
      http.Method = "POST"; 

      http.ContentType = "application/json"; 

      Encoding encoder = Encoding.UTF8; 
      byte[] data = encoder.GetBytes(dataPoint.ToJson() + Environment.NewLine); 
      http.Method = "POST"; 
      http.ContentType = "application/json; charset=utf-8"; 
      http.ContentLength = data.Length; 
      using (Stream stream = http.GetRequestStream()) 
      { 
       stream.Write(data, 0, data.Length); 
       stream.Close(); 
      } 

      WebResponse response = http.GetResponse(); 

      var streamOutput = response.GetResponseStream(); 
      StreamReader sr = new StreamReader(streamOutput); 
      string content = sr.ReadToEnd(); 
      Console.WriteLine(content); 
     } 
     catch (WebException exc) 
     { 
      StreamReader reader = new StreamReader(exc.Response.GetResponseStream()); 
      var content = reader.ReadToEnd(); 
     } 

        return ; 
    } 

,我明確設置爲false SendChunked財產。

注意其他要求,如:完美

public static async Task<bool> Connect(Uri uri) 
     { 
      HttpWebRequest http = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:4242/api/version"); 
      http.SendChunked = false; 
      http.Method = "GET"; 
      // http.Headers.Clear(); 
      //http.Headers.Add("Content-Type", "application/json"); 
      http.ContentType = "application/json"; 
      WebResponse response = http.GetResponse(); 

      var stream = response.GetResponseStream(); 
      StreamReader sr = new StreamReader(stream); 
      string content = sr.ReadToEnd(); 
      Console.WriteLine(content); 
      return true; 

     } 

工作。 我相信我正在做一些真正錯誤的事情。 我想從頭重新實現Sockets中的HTTP。

回答

0

我找到了一個我想在這裏分享的解決方案。 我使用Wireshark的嗅探我的包,我發現,這頭說:

Expect: 100-continue\r\n 

(見https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html 8.2.3)

這是罪魁禍首。我讀過菲爾哈克的文章http://haacked.com/archive/2004/05/15/http-web-request-expect-100-continue.aspx/,發現HttpWebRequest默認會放這個頭文件,除非你讓它停止。在本文中,我發現使用ServicePointManager可以做到這一點。

把下面的代碼放在我的方法之上,宣告了http對象時,使得它的工作非常好,解決了我的問題:

  var uri = new Uri("http://127.0.0.1:4242/api/put"); 
      var spm = ServicePointManager.FindServicePoint(uri); 
      spm.Expect100Continue = false; 
      HttpWebRequest http = (HttpWebRequest)WebRequest.Create(uri); 
      http.SendChunked = false;