我正在尝试执行简单的"请求正文搜索"在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
请求的内容正文。或者有解决方法吗?
答案 0 :(得分:3)
将Method
更改为POST
是一种解决方法。
request.Method = "POST";
MSDN说明如果使用ProtocolViolationException
或GetResponseStream()
方法调用GET
方法,则会引发HEAD
。