Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to execute a simple "request body search" on Elasticsearch like the following example but using .NET instead of curl

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

Below is my .NET code.

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();
    }
}

However, I am getting the following error.

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()))

Is there any way I can send a content-body with a GET request using standard .NET classes. Or is there a workaround?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

Changing the Method to POST is a workaround.

request.Method = "POST";

MSDN states that a ProtocolViolationException will be thrown if the GetResponseStream() method is called with a GET or HEAD method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...