远程服务器未经授权返回错误(401)

时间:2014-08-13 13:16:35

标签: asp.net vb.net

用于在Android设备上获取通知的书面代码。 在这添加了该Android应用程序的设备ID和注册ID和应用程序ID,但我运行此页面获取此错误.... 远程服务器返回错误:(401)未经授权。

 private void AndroidPush()
    {
        string regId = "[the regid]";

        // applicationID means google Api key                                                                                                     
        var applicationID = "[the key]";
        //ProjectID (from API Console- google code)                                        
        var SENDER_ID = "[the id]";
        var value = Text1.Text; //message text box  
        WebRequest tRequest;
        tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
        tRequest.Method = "post";
        tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
        tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
        tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

        tRequest.UseDefaultCredentials = true;

        tRequest.PreAuthenticate = true;

        tRequest.Credentials = CredentialCache.DefaultCredentials;

        string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
                  + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + regId + "";

        Byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        tRequest.ContentLength = byteArray.Length;



        Stream dataStream = tRequest.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();



        WebResponse tResponse = tRequest.GetResponse();
        dataStream = tResponse.GetResponseStream();
        StreamReader tReader = new StreamReader(dataStream);
        String sResponseFromServer = tReader.ReadToEnd();   //Get response from GCM server.  

        Label3.Text = sResponseFromServer;      //Assigning GCM response to Label text 
        tReader.Close();
        dataStream.Close();
        tResponse.Close();
    }

1 个答案:

答案 0 :(得分:0)

如果您没有输入用户名和密码,则无法连接到远程服务器 Check This Answer可能会有所帮助。