Home > Software design >  Make a Rest Client in .NET Framework 4.0
Make a Rest Client in .NET Framework 4.0

Time:02-04

I am very new to .NET Framework especially 4.0 and have not found any article nor documentation regarding how to make a REST API request with .NET Framework. I know the request to the URL was made correctly as it generated a an access_token both in curl and also Python

enter image description here

Below is the one made in Python

enter image description here

The on above was used with the requests library from Python below is also an example of a curl request.

curl --location --request POST 'https://****-****/sso/auth/v1/service' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_secret=999999-llll-llll-llll-abcdghe' \
--data-urlencode 'client_id=ssuper-integration-friendly-hml' \
--data-urlencode 'grant_type=client_credentials'

However I have been trying all week to make a client REST API in .NET Framework 4.0 and have not been sucessful please help me!

Thanks!

CodePudding user response:

using System.Net;
using System;
using System.IO;
using System.Net;
using System.Text;

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        var app = builder.Build();

string url = "***********";
        string clientSecret = "*******";
        string clientId = "************";
        string grantType = "**********";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        string postData = $"client_secret={clientSecret}&client_id={clientId}&grant_type={grantType}";
        byte[] data = Encoding.ASCII.GetBytes(postData);

        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            string responseText = reader.ReadToEnd();
            Console.WriteLine(responseText);
        }
   
    }
}

I figured it out this is the correct way

  • Related