一尘不染

无法发送带有GET请求的内容主体

elasticsearch

我正在尝试在Elasticsearch上执行简单的“请求正文搜索”,如以下示例所示,但使用.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()))

有什么方法可以GET使用标准.NET类发送带有请求的内容主体。还是有解决方法?


阅读 1181

收藏
2020-06-22

共1个答案

一尘不染

将更Method改为POST解决方法。

request.Method = "POST";

MSDN声明,ProtocolViolationException如果GetResponseStream()使用GETor
HEAD方法调用该方法,则将引发a 。

2020-06-22