Click here to Skip to main content
15,881,870 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to consume rest api having post method in my project (web)/Windows service(C#).

Url : https://sampleurl.com/api1/token


I need to pass username and password for generating token. I have written code like this.

string sURL = "https://sampleurl.com/api1/token/Actualusername/Actualpassword";
            WebRequest wrGETURL;
            wrGETURL = WebRequest.Create(sURL);

            wrGETURL.Method = "POST";
            wrGETURL.ContentType = @"application/json; charset=utf-8";
            wrGETURL.ContentLength = 0;
            HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;

            Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
            // read response stream from response object
            StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
            // read string from stream data
            string  strResult = loResponseStream.ReadToEnd();
            // close the stream object
            loResponseStream.Close();
            // close the response object
            webresponse.Close();

            Response.Write(strResult);



am getting error: No connection could be made because the target machine actively refused it

Is it right way to consume rest api in C#?

What I have tried:

string sURL = "https://sampleurl.com/api1/token/Actualusername/Actualpassword";
            WebRequest wrGETURL;
            wrGETURL = WebRequest.Create(sURL);

            wrGETURL.Method = "POST";
            wrGETURL.ContentType = @"application/json; charset=utf-8";
            wrGETURL.ContentLength = 0;
            HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse;

            Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
            // read response stream from response object
            StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc);
            // read string from stream data
            string  strResult = loResponseStream.ReadToEnd();
            // close the stream object
            loResponseStream.Close();
            // close the response object
            webresponse.Close();

            Response.Write(strResult);
Posted
Updated 16-May-17 21:52pm

1 solution

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900