2016-04-25 48 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;