Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

c# - How do I use HttpWebRequest with GET method

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...