简体   繁体   中英

HttpWebRequest returns null ResponseStatusCode

I'm writing a background audio agent that plays music from an online stream and also periodically checks for updates in the track name and artist. I'm attempting to use an HttpWebRequest object to get the name and artist, but whenever I call HttpWebResponse trackResponse = (HttpWebResponse)trackRequest.EndGetResponse(result); the error below is thrown.

A first chance exception of type 'System.Net.WebException' occurred in System.Windows.dll

The stack trace for the WebException is the following:

at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at AudioPlaybackAgent.AudioPlayer.TrackCallback(IAsyncResult result)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)
at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()

Digging further into the trackRequest object, I find this:

ResponseStatusCode = 'trackRequest.ResponseStatusCode' threw an exception of type 'System.NullReferenceException'

and further into that, I find this:

at System.Net.HttpWebRequest.get_ResponseStatusCode()
at AudioPlaybackAgent.AudioPlayer.TrackCallback(IAsyncResult result)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)
at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()

Here is the code I am using. The TrackTimerTick function is called every 20 seconds by a Timer.

public static void TrackTimerTick(object state) {
        try {
            if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing) {
                // Create a HttpWebrequest object to the desired URL.
                HttpWebRequest trackRequest = (HttpWebRequest)HttpWebRequest.Create("<track/artist url");
                // Start the asynchronous request.
                IAsyncResult result = (IAsyncResult)trackRequest.BeginGetResponse(new AsyncCallback(TrackCallback), trackRequest);
            }
        } catch (WebException e) {
            Debug.WriteLine(e.Message);
        } catch (Exception e) {
            Debug.WriteLine(e.Message);
        }
    }


    public static void TrackCallback(IAsyncResult result) {
        // State of request is asynchronous.
        HttpWebRequest trackRequest = (HttpWebRequest)result.AsyncState;
        HttpWebResponse trackResponse = (HttpWebResponse)trackRequest.EndGetResponse(result); // WebException thrown here

        using (StreamReader httpwebStreamReader = new StreamReader(trackResponse.GetResponseStream())) {
            string results = httpwebStreamReader.ReadToEnd();
            XDocument trackXml = XDocument.Load(results);

            string title = (from t in trackXml.Descendants("channel") select t.Element("title").Value).First<string>();
            string artist = (from t in trackXml.Descendants("channel") select t.Element("artist").Value).First<string>();
            if (BackgroundAudioPlayer.Instance.Track != null) {
                AudioTrack track = BackgroundAudioPlayer.Instance.Track;
                track.BeginEdit();
                track.Title = title;
                track.Artist = artist;
                track.EndEdit();
            }

        }
        trackResponse.Close();


    }

Can anyone help me fix this problem? Thank you in advance.

The problem is that you call NotifyComplete() before the response is arrive. I don't understand fully what happens, but you initiate the request, you call NotifyComplete, the OS froze the agent's process, then the next time the agent wakes up the WebClient immediately throws an exception, probably by design.

So the solution is to don't call NotifyComplete until you got the response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM