如何使用HttpWebRequest的使用GET方法如何使用、方法、HttpWebRequest、GET

2023-09-02 23:49:44 作者:の喜洋洋一样的男生

我有以下的code当方法是POST,它工作得很好,但改变为GET不工作:

  HttpWebRequest的要求= NULL;
请求= HttpWebRequest.Create(URI),为的HttpWebRequest;
request.ContentType =应用/的X WWW的形式urlen codeD;字符集= UTF-8;
request.Method =POST; //不一起工作GET

request.BeginGetRequestStream(this.RequestCallback,NULL);
 

我收到了 ProtocolViolationException 异常的GET的方法。

编辑:使用反射具有一看后,似乎有一个明确检查了GET方法,如果它被设置为它引发异常

EDIT2:我已经更新了我的code以下内容,但它仍然抛出一个异常,当我打电话EndGetResponse()

 如果(request.Method ==GET)
{
    request.BeginGetResponse(this.ResponseCallback,状态);
}
其他
{
    request.BeginGetRequestStream(this.RequestCallback,状态);
}
 

在我的功能,ResponseCallback,我有这样的:

  HttpWebResponse响应=(HttpWebResponse)request.EndGetResponse(asyncResult);
 
C 使用HttpWebRequest 实现简单的get和post请求

会抛出异常也是如此。

答案

以上code现在的工作,我已经忘了取出来这是导致异常在年底抛出的内容类型行。 +1 tweakt&安培;回答乔恩。

工作code是现在如下:

  HttpWebRequest的要求= NULL;
请求= HttpWebRequest.Create(URI),为的HttpWebRequest;
request.Method =GET; //支持Post太

如果(request.Method ==GET)
{
    request.BeginGetResponse(this.ResponseCallback,状态);
}
其他
{
    request.BeginGetRequestStream(this.RequestCallback,状态);
}
 

解决方案

这是specified在文档。基本上GET请求不是为了遏制机构,因此没有合理的理由叫 BeginGetRequestStream

I have the following code which works just fine when the method is "POST", but changing to "GET" doesn't work:

HttpWebRequest request = null;
request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Method = "POST"; // Doesn't work with "GET"

request.BeginGetRequestStream(this.RequestCallback, null);

I get a ProtocolViolationException exception with the "GET" method.

Edit: After having a look using Reflector, it seems there is an explicit check for the "GET" method, if it's set to that it throws the exception.

Edit2: I've updated my code to the following, but it still throws an exception when I call EndGetResponse()

if (request.Method == "GET")
{
    request.BeginGetResponse(this.ResponseCallback, state);
}
else
{
    request.BeginGetRequestStream(this.RequestCallback, state);
}

In my function, ResponseCallback, I have this:

HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

Which throws the exception as well.

Answer

The above code now works, I had forgotten to take out the Content-Type line which was causing the exception to be thrown at the end. +1 to tweakt & answer to Jon.

The working code is now below:

HttpWebRequest request = null;
request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.Method = "GET";// Supports POST too

if (request.Method == "GET")
{
    request.BeginGetResponse(this.ResponseCallback, state);
}
else
{
    request.BeginGetRequestStream(this.RequestCallback, state);
}

解决方案

This is specified in the documentation. Basically GET requests aren't meant to contain bodies, so there's no sensible reason to call BeginGetRequestStream.