【问题标题】:Cannot send content-body with GET request无法使用 GET 请求发送内容正文
【发布时间】:2014-12-11 09:46:09
【问题描述】:

我正在尝试在 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 请求的内容主体。或者有什么解决方法?

【问题讨论】:

    标签: .net get elasticsearch


    【解决方案1】:

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

    request.Method = "POST";
    

    MSDN 声明如果使用GETHEAD 方法调用GetResponseStream() 方法,将抛出ProtocolViolationException

    【讨论】:

    • 我遇到了同样的问题,但方法必须是 GET ,我无权将其从 GET 更改为 POST,是否有其他解决方法?
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多