开发者

Can't find HttpWebRequest.GetResponse() in WP7 Project

开发者 https://www.devze.com 2023-03-05 19:03 出处:网络
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 the Scrape() method). They all basically do the same thi

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 the Scrape() 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.

Well to be more accurate, this is a Windows Phone game, created in XNA 4.0

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

精彩评论

暂无评论...
验证码 换一张
取 消