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

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

.net - Cannot send content-body with GET request

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...