WebRequest.GetRequestStreamAsync() method timesout each time for MNS access token

这一生的挚爱 提交于 2020-01-06 14:54:38

问题


I am trying to get the access token from MNS for Push notifications and the WebRequest.GetRequestStreamAsync() method timesout each time. Any suggestions?

Reference: http://msdn.microsoft.com/en-us/library/windows/apps/hh913756.aspx

Below is the code I use

        HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("https://login.live.com/accesstoken.srf");
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";

        string postString = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",
                              SID,
                              SECRET_KEY);
        byte[] data = Encoding.UTF8.GetBytes(postString);
        Stream newStream = await webRequest.GetRequestStreamAsync();
        newStream.Write(data, 0, data.Length);

回答1:


Try rewriting it like this and see if it makes a difference. I've sometimes had problems with HttpWebRequest where WebRequest worked fine. Also make sure you close your streams.

    WebRequest webRequest = WebRequest.Create("https://login.live.com/accesstoken.srf");
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    string postString = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",
                          SID,
                          SECRET_KEY);
    byte[] data = Encoding.UTF8.GetBytes(postString);
    Stream newStream = await webRequest.GetRequestStreamAsync();
    newStream.Write(data, 0, data.Length);
    newStream.Close();

    WebResponse response = webRequest.GetResponse();
    StreamReader requestReader = new StreamReader( response.GetResponseStream() );
    string webResponse = requestReader.ReadToEnd();
    response.Close();



回答2:


Call .ConfigureAwait(false) on your Async method.

This blog post should explain the why and how.




回答3:


We had the same problem and it turned out to be a problem in different place than one would originally guess.

You need to .Dispose() or at least .Close() the response that you get from .GetResponseAsync, otherwise the next call to .GetRequestStreamAsync hangs.

It seems that the code behind this holds some limited (rather low) amount of sockets or locks, that disallow further requests to even begin until previous request has completed.



来源:https://stackoverflow.com/questions/17032338/webrequest-getrequeststreamasync-method-timesout-each-time-for-mns-access-toke

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