开发者

Alternative to this Http Request

开发者 https://www.devze.com 2023-01-24 09:35 出处:网络
I have a class that goes and grabs some data and returns it as a string. While this object is working there is a spinning icon letting the user know work is being done. The problem is the code exits b

I have a class that goes and grabs some data and returns it as a string. While this object is working there is a spinning icon letting the user know work is being done. The problem is the code exits before the response comes back. I stuck a

while(response == null)

In just to see whats going on and the

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

is not firing. It fires ok in a console application so I am putting this down to something I am doing that silverlight doesn't like, heres the full code:

public class HttpWorker
{
    private HttpWebRequest request;
    private HttpWebResponse response;
    private string responseAsString;
    private string url;

    public HttpWorker()
    {

    }

    public string ReadFromUrl(string Url)
    {
        url = Url;
        request = (HttpWebRequest)WebRequest.Create(url);

        request.CookieContainer = new CookieContainer();
        request.AllowAutoRedirect = true;
        request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";

        AsyncRequest(); // The Demon!

        return responseAsString;
    }

    private void AsyncRequest()
    {
        request.BeginGetResponse(new AsyncCallback(FinaliseAsyncRequest), null);
    }

    private void FinaliseAsyncRequest(IAsyncResult AsyncResult)
    {
        response = (HttpWebResponse)request.EndGetResponse(AsyncResult);


        if (response.StatusCode == HttpStatusCode.OK)
        {
            // Create the stream, encoder and reader.
            Stream responseStream = response.GetResponseStream();
            Encoding streamEncoder = Encoding.UTF8;
            StreamReader responseReader = new StreamReader(responseStream, streamEncoder);
            responseAsString = responseReader.ReadToEnd();
        }
        else
        {
            throw new Exception(String.Format("Response Not Val开发者_开发知识库id {0}", response.StatusCode));
        }
    }

}


Are you going into the busy loop with (while response == null) on the UI thread? The async callback for the HttpRequest will be delivered on the UI thread, so if you're looping on that same thread, the callback can never run. You need to return to allow the main message loop to run, and then your async callback will be delivered.

Your design above suggests that what you really want is a synchronous fetch anyway. Forget the callback and just call FinaliseAsyncRequest inside ReadFromUrl yourself. The UI will hang until the request completes, but it sounds like that's what you want.


I posted a working sample here of using WebClient and HttpWebRequest.

WebClient, HttpWebRequest and the UI Thread on Windows Phone 7

Note the latter is preferred for any non trivial processing to avoid blocking the UI.

Feel free to reuse the code.


The easiest way to get a string from a web server is to use WebClient.DownloadStringAsync() (MSDN docs).

Try something like this:

private void DownloadString(string address)
{
    WebClient client = new WebClient();
    Uri uri = new Uri(address);

    client.DownloadStringCompleted += DownloadStringCallback;
    client.DownloadStringAsync(uri);

    StartWaitAnimation();
}


private void DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
{
    // Do something with e.Result (which is the returned string)

    StopWaitAnimation();
}

Note that the callback executes on the UI thread and so you should only use this method if your callback method is not doing very much as it will block the UI while it executes.

If you need more control over the web request then you can use HttpWebRequest.

If you really must imitate synchronous behaviour have a look at Faking synchronous calls in Silverlight WP7

0

精彩评论

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

关注公众号