I'm trying to send a GET request using HttpWebRequest.
I've found a lot of examples all over the web (for example, this one...just go down to theScrape()
method). They all basically do the same thing:
Create a HttpWebRequest
object by using WebRequest.Create(URL) and casting it to HttpWebRequest
, then getting the response by using the GetResponse()
method from HttpWebRequest
.
Thing is, GetResponse()
doesn't seem to exist in either HttpWebRequest
or WebRequest
(which is its base class). My only option is to use BeginGetResponse()
.
The only thing I found is that GetResponse()
is synchronous, while BeginGetResponse()
is asynchronous, and that Silverlight only allows the asynchronous one. Well,开发者_如何学编程 that doesn't help me at all, since the whole thing is an XNA project, and this is a simple C# class I created inside.
HttpWebRequest webRequest = WebRequest.Create(URL) as HttpWebRequest;
StreamReader responseReader = new StreamReader(
webRequest.GetResponse().GetResponseStream());
Does anyone have any idea as to why I don't have GetResponse()
?
XNA 4 for Windows Phone 7 can only make asynchronous calls. You might find the code at the bottom of this post helpful as well.
Code from that post:
protected override void Initialize()
{
string webServiceAddress = @"http://localhost/service/service1.asmx";
string methodName = "HelloWorld";
string webServiceMethodUri = string.Format("{0}/{1}", webServiceAddress, methodName);
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(webServiceMethodUri);
httpWebRequest.Method = "POST";
httpWebRequest.BeginGetResponse(Response_Completed, httpWebRequest);
base.Initialize();
}
void Response_Completed(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string xml = streamReader.ReadToEnd();
using(XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
reader.MoveToContent();
reader.GetAttribute(0);
reader.MoveToContent();
message = reader.ReadInnerXml();
}
}
}
精彩评论