无法使用GET请求发送content-body [英] Cannot send content-body with GET request

查看:2406
本文介绍了无法使用GET请求发送content-body的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在弹性搜索上执行一个简单的请求正文搜索,如以下示例,但使用.NET而不是卷曲

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

但是,我收到以下错误。 p>

 无法使用此动词类型发送内容正文。 
...
异常详细信息:System.Net.ProtocolViolationException:无法使用此动词类型发送内容正文。
...
第54行:使用(var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))

有什么办法可以使用标准的.NET类发送一个包含 GET 请求的内容体。或者有解决方法吗?

解决方案

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

  request.Method =POST; 

GET 或 HEAD 方法调用GetResponseStream()方法。 >

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?

解决方案

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.

这篇关于无法使用GET请求发送content-body的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆