IIS asp.net C# API Post Method error "'The remote server returned an error: (403) Forbidden.'"

663 views Asked by At

I have via gupshup created a viber bot. I run my WebForm application with IIS server in win 10. I tried to send a message to my viberbot via api post method but c# strangle me.(I tested url and parameters with success)

here is my code :

protected void viber_msg(String viberid, String strmsg)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.gupshup.io/sm/api/bot/mybotname/msg?apikey=mykey");
    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
    httpWebRequest.Method = "POST";

   
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "context={'botname':'mybotname','channeltype':'viber','contextid':'viberid','contexttype':'p2p'}&message="+strmsg;
        streamWriter.Write(json);
    }
    
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    viber_msg("viberuserID", "This is a message");
}

The error I am getting is "System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'" Also tried with POSTMAN and getting "message": "Invalid authentication credentials" Thnx in advance...

1

There are 1 answers

1
David Dan On BEST ANSWER
protected void viber_msg(String viberid, String message)
{
    var client = new RestClient("https://api.gupshup.io/sm/api/bot/mybot/msg?apikey=myapikey");
    client.Timeout = -1;
    var request = new RestRequest(Method.POST);
    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
    request.AddParameter("context", "{\"botname\": \"mybot\",\"channeltype\" :\"viber\",\"contextid\": \""+viberid+"\",\"contexttype\": \"p2p\"}");
    request.AddParameter("message", message);
    IRestResponse response = client.Execute(request);
} 

protected void Button1_Click(object sender, EventArgs e)
{
    viber_msg("viberid", "message");
}

}

RestSharp Library!!!