How do I use HttpWebRequest with GET method

2019-01-14 15:55发布

问题:

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

回答1:

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



回答2:

Does it make sense for a GET request to send a Content-Type? Did you try removing the third line?



回答3:

BeginGetRequestStream is used to get a stream specifically for writing data to the request. This is not applicable to GET requests.

The documentation for the BeginGetRequestStream method states explicitly that the method will throw a ProtocolViolationException if the Method is GET or HEAD.

Morale: read the docs ;-)



回答4:

It is specified in the documentation for the GetRequestStream that it will throw a ProtocolViolationException if the method is GET. However, I cannot find anything in the HTTP spec to suggest that this is actually an HTTP protocol violation. Consider this a challenge.