简体   繁体   中英

remote server returned an error (401) unauthorized

Written code to get the notification on android device. In this added the device id and registration id and application id of that android application but i run this page getting this error.... The remote server returned an error: (401) Unauthorized.

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

You can't connect to remote server if you don't enter Username and Password
Check This Answer might be helpful.

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