无法使用此动词类型发送内容正文

时间:2010-10-20 19:28:56

标签: .net webrequest

我在.NET 2.0应用程序中运行此异常(ProtocolViolationException)(在Windows Mobile 6标准模拟器上运行)。令我困惑的是,据我所知,我没有添加任何内容正文,除非我无意中以某种方式完成了它。我的代码如下(非常简单)。还有什么我需要做的来说服.NET,这只是一个http GET吗?

谢谢, 布赖恩

//run get and grab response
WebRequest request = WebRequest.Create(get.AbsoluteUri + args);
request.Method = "GET";
Stream stream = request.GetRequestStream();           // <= explodes here
XmlTextReader reader = new XmlTextReader(stream);

4 个答案:

答案 0 :(得分:140)

不要简单地获取请求流。 GET请求通常有正文(即使它是not technically prohibited by HTTP)而WebRequest不支持它 - 但这就是调用GetRequestStream的原因,提供请求的正文数据。

鉴于您正在尝试从流中读取,我认为您实际上想要获取响应并从中读取响应流:< / p>

WebRequest request = WebRequest.Create(get.AbsoluteUri + args);
request.Method = "GET";
using (WebResponse response = request.GetResponse())
{
    using (Stream stream = response.GetResponseStream())
    {
        XmlTextReader reader = new XmlTextReader(stream);
        ...
    }
}

答案 1 :(得分:2)

因为您没有指定标题。

我添加了一个扩展示例:

var request = (HttpWebRequest)WebRequest.Create(strServer + strURL.Split('&')[1].ToString());

标题(参考请求,p_Method);

方法标题:

private void Header(ref HttpWebRequest p_request, string p_Method)
{
    p_request.ContentType = "application/x-www-form-urlencoded";
    p_request.Method = p_Method;
    p_request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows CE)";
    p_request.Host = strServer.Split('/')[2].ToString();
    p_request.Accept = "*/*";
    if (String.IsNullOrEmpty(strURLReferer))
    {
        p_request.Referer = strServer;
    }
    else
    {
        p_request.Referer = strURLReferer;
    }
    p_request.Headers.Add("Accept-Language", "en-us\r\n");
    p_request.Headers.Add("UA-CPU", "x86 \r\n");
    p_request.Headers.Add("Cache-Control", "no-cache\r\n");
    p_request.KeepAlive = true;
}

答案 2 :(得分:2)

我使用Flurl.Http遇到类似的问题:

Flurl.Http.FlurlHttpException: Call failed. Cannot send a content-body with this verb-type. GET http://******:8301/api/v1/agents/**** ---> System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.

问题是我在创建IFlurlRequest时使用了.WithHeader("Content-Type", "application/json")

答案 3 :(得分:-4)

请在阅读回复流之前设置请求内容类型;

 request.ContentType = "text/xml";