HttpWebRequest returns null ResponseStatusCode

匆匆过客 提交于 2019-12-11 08:22:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/9643896/httpwebrequest-returns-null-responsestatuscode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!