3

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

I 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#?

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
Jui Test
  • 2,399
  • 14
  • 49
  • 76
  • Check this url http://stackoverflow.com/questions/18347055/calling-a-rest-api-with-username-and-password-how-to – S.K May 17 '17 at 07:04
  • @HoneyBadger,bymistakenly added sql tag. – Jui Test May 17 '17 at 07:17
  • The rest server is not running, a firewall is blocking access to it or the url isn't right. I don't know about other browsers, but for Chrome there is an extension that allows you to test such requests: https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo – C.Evenhuis May 17 '17 at 07:17
  • 2
    So this API requires a POST method with no content and the username/password in the url? That seems like a really bad idea, maybe you are supposed to put the user credentials in the request body and send it? – robjam May 17 '17 at 07:19
  • @robjam,thanks for ur help.Can u pls update the code?How to pass parameter in request body not in url?I – Jui Test May 17 '17 at 07:24
  • Looks very non standard. Do you have any specifications for /api1/token end point? – Mardoxx May 17 '17 at 07:25
  • @JuiTest How can we update your code to work with that api without knowing anything about that api? There should be a documentation how to consume the api. (just as an example the imgur api docs https://api.imgur.com/oauth2 ) – Sir Rufo May 17 '17 at 07:53

2 Answers2

3

This all very much depend on the API's documentation, but to write data to the request body, get the request stream and then write the string to the stream. again, this depends on what the API you are authenticating with and without knowing which one is guesswork on my part.

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

        wrGETURL.Method = "POST";
        wrGETURL.ContentType = @"application/json; charset=utf-8";
        using (var stream = new StreamWriter(wrGETURL.GetRequestStream()))
        {
            var bodyContent = new
            {
                username = "Actualusername",
                password = "Actualpassword"
            }; // This will need to be changed to an actual class after finding what the specification sheet requires.

            var json = JsonConvert.SerializeObject(bodyContent);

            stream.Write(json);
        }
        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);
robjam
  • 969
  • 1
  • 11
  • 24
0

Consume API with Basic Authentication in C#

 class Program
{
    static void Main(string[] args)
    {
        BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
        BaseResponse response = new BaseResponse();
        BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
    }


    public async Task<BaseResponse> GetCallAsync(string endpoint)
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            else
            {
                baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
                baseresponse.StatusCode = (int)response.StatusCode;
            }
            return baseresponse;
        }
        catch (Exception ex)
        {
            baseresponse.StatusCode = 0;
            baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
        }
        return baseresponse;
    }
}


public class BaseResponse
{
    public int StatusCode { get; set; }
    public string ResponseMessage { get; set; }
}

public class BaseClient
{
    readonly HttpClient client;
    readonly BaseResponse baseresponse;

    public BaseClient(string baseAddress, string username, string password)
    {
        HttpClientHandler handler = new HttpClientHandler()
        {
            Proxy = new WebProxy("http://127.0.0.1:8888"),
            UseProxy = false,
        };

        client = new HttpClient(handler);
        client.BaseAddress = new Uri(baseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        baseresponse = new BaseResponse();

    }
}
Pramod Lawate
  • 615
  • 1
  • 7
  • 21