简体   繁体   中英

System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse()

I want to sent push notification via parse.com and i have webservice like that

[WebMethod] public bool pushNotification(string pushMessage) { bool isPushMessageSend = false;

    string postString = "";
    string urlpath = "https://api.parse.com/1/push";
    //var httpWebRequest = (HttpWebRequest)WebRequest.Create(urlpath);

    System.Net.WebRequest request = System.Net.HttpWebRequest.Create(urlpath);

    request.UseDefaultCredentials = true;

    request.PreAuthenticate = true;

    request.Credentials = CredentialCache.DefaultCredentials;




    postString = "{ \"channels\": [ \"Trials\"  ], " +
                     "\"data\" : {\"alert\":\"" + pushMessage + "\"}" +
                     "}";
    request.ContentType = "application/json";
    request.ContentLength = postString.Length;
    request.Headers.Add("APP ID", "My Parse App Id");
    request.Headers.Add("REST API KEY", "My Rest API Key");
    request.Method = "POST";
    StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());
    requestWriter.Write(postString);
    requestWriter.Close();
    //var httpResponse = (HttpWebResponse)request.GetResponse();
    System.Net.WebResponse response = request.GetResponse();
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
        JObject jObjRes = JObject.Parse(responseText);
        if (Convert.ToString(jObjRes).IndexOf("true") != -1)
        {
            isPushMessageSend = true;
        }
    }

    return isPushMessageSend;
}

I had error like this

System.Net.WebException: The remote server returned an error: (401) Unauthorized.
   at System.Net.HttpWebRequest.GetResponse()
   at WebService.pushNotification(String pushMessage) in c:\Users\Hurkan Seyhan\desktop\website3\App_Code\WebService.cs:line 488

How can I solve this problem?

according to their documentation ( https://parse.com/docs/push_guide#sending-channels/REST ) I think that mistake in your headers

instead of

request.Headers.Add("[YOUR APP ID]", "My Parse App Id");
request.Headers.Add("[YOUR REST API KEY]", "My Rest API Key");

you probably should write the following:

request.Headers.Add("X-Parse-Application-Id", "[YOUR APP ID]");
request.Headers.Add("X-Parse-REST-API-Key", "[YOUR REST API KEY]");

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