无法使用GET请求发送内容正文

时间:2014-12-11 09:46:09

标签: .net get elasticsearch

我正在尝试执行简单的"请求正文搜索"在Elasticsearch上,如following example但使用.NET而不是curl

$ curl -XGET 'http://localhost:9200/twitter/tweet/_search' -d '{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}
'

以下是我的.NET代码。

var uri = "http://localhost:9200/myindex/_search";
var json = "{ \"query\" : { \"term\" : { \"user\" : \"kimchy\" } } }";

var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.ContentType = "text/json";
request.Method = "GET";

var responseString = string.Empty;

using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
{
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();

    var response = (System.Net.HttpWebResponse)request.GetResponse();
    using (var streamReader = new System.IO.StreamReader(response.GetResponseStream()))
    {
        responseString = streamReader.ReadToEnd();
    }
}

但是,我收到以下错误。

Cannot send a content-body with this verb-type.
...
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
...
Line 54: using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))

有没有办法可以使用标准.NET类发送带有GET请求的内容正文。或者有解决方法吗?

1 个答案:

答案 0 :(得分:3)

Method更改为POST是一种解决方法。

request.Method = "POST";

MSDN说明如果使用ProtocolViolationExceptionGetResponseStream()方法调用GET方法,则会引发HEAD