无法使用 GET 请求发送内容正文 [英] Cannot send content-body with GET request
问题描述
我正在尝试在 Elasticsearch 上执行一个简单的请求正文搜索",例如 以下示例 但使用 .NET 而不是 curl
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" }
}
}
'
下面是我的 .NET 代码.
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()))
有什么方法可以使用标准 .NET 类发送带有 GET
请求的内容正文.或者有解决方法吗?
Is there any way I can send a content-body with a GET
request using standard .NET classes. Or is there a workaround?
推荐答案
将 Method
更改为 POST
是一种解决方法.
Changing the Method
to POST
is a workaround.
request.Method = "POST";
MSDN 指出如果使用 GET
或 HEAD
方法调用 GetResponseStream()
方法,则将抛出 ProtocolViolationException
.
MSDN states that a ProtocolViolationException
will be thrown if the GetResponseStream()
method is called with a GET
or HEAD
method.
这篇关于无法使用 GET 请求发送内容正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!