【问题标题】:HttpWebRequest returns null ResponseStatusCodeHttpWebRequest 返回 null ResponseStatusCode
【发布时间】:2021-08-31 21:54:45
【问题描述】:

我正在编写一个后台音频代理,它可以播放在线流中的音乐,并定期检查曲目名称和艺术家的更新。我正在尝试使用 HttpWebRequest 对象来获取名称和艺术家,但每当我调用 HttpWebResponse trackResponse = (HttpWebResponse)trackRequest.EndGetResponse(result); 时,都会引发以下错误。

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

WebException 的堆栈跟踪如下:

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()

进一步挖掘 trackRequest 对象,我发现:

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

更进一步,我发现:

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()

这是我正在使用的代码。 TrackTimerTick 函数由 Timer 每 20 秒调用一次。

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


    }

谁能帮我解决这个问题?提前谢谢你。

【问题讨论】:

  • 你不会碰巧从两个线程访问响应状态吧?
  • 我不这么认为,因为 TrackCallback 是我引用响应的唯一位置。

标签: c# silverlight windows-phone-7.1 windows-phone-7


【解决方案1】:

问题是您在响应到达之前调用了 NotifyComplete()。我不完全了解会发生什么,但是您发起请求,调用 NotifyComplete,操作系统冻结了代理的进程,然后代理下次唤醒 WebClient 立即抛出异常,可能是设计使然。

所以解决方案是在收到响应之前不要调用 NotifyComplete。

【讨论】:

  • 你能解释一下吗?我尝试移动 NotifyComplete()s 并设法让曲目文本通过,但是当我单击我的应用内暂停按钮时,音乐不会暂停。能多提点建议吗?
  • 好吧,我从来没有写过任何音频背景代理,我最好的想法是你仍然没有在正确的时间调用 NotifyComplete。可能是一个问题的第一件事是您正在使用计时器。由于该过程在控制命令之间被冻结,因此计时器的滴答事件不会在命令之间触发。如果您真的想在您的音频代理中执行 webrequests(我不确定这是一个好主意,也不是您真的需要。)尝试在 PlayStateChanged 中启动请求并在响应回调中调用 NotifyComplete。如果没有更多信息,这是我最好的主意。
  • 谢谢,有道理。我想要做的是让音频后台代理每 20-30 秒查询一次服务器以获取新的曲目数据,即使启动音频代理的主应用程序已停用。这可能吗?
【解决方案2】:

在我的情况下,我必须查看我的项目错误日志,其中通常会引发异常,它正在打印消息 Unable to create an SSL/TLS secure channel. in System.Net.HttpWebRequest.GetResponse(),为了解决这个问题,我在请求之前添加了 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;,但您可以将其执行在您的入门方法或类上。我认为您可以做的其他事情是在 try 和 catch 异常中添加响应

try
    {
        var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            Response response = new JavaScriptSerializer().Deserialize<Response>(result);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

这里是你的响应类

public class Response
{
    public string value_02 { get; set; }
    public string value_03 { get; set; }
    public string value_04 { get; set; }
    public string value_05 { get; set; }
    public string value_05 { get; set; }
}

事实上对我来说是例外

Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.dll
Exception thrown: 'System.ObjectDisposedException' in System.dll
Exception thrown: 'System.Net.WebException' in System.dll
Exception thrown: 'System.Net.WebException' in System.dll
Exception thrown: 'System.NullReferenceException'

我已经添加来解决我的问题

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

解决了我的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多