Skip to main content

Notifications

Announcements

No record found.

Customer Service forum

How can i consume rest api of https kind for POST request in c#

(0) ShareShare
ReportReport
Posted on by Microsoft Employee

How can i consume rest api of https kind for POST request in c#

I have rest api of https and i need to send data from crm in json format with 'Post' request. How can i consume and send POST data to them?

Categories:
  • nickmanny Profile Picture
    nickmanny 136 on at
    RE: How can i consume rest api of https kind for POST request in c#

    // Set the base address of the API
    client.BaseAddress = new Uri("https://api.example.com");
    
    // Set the content to be sent in the request
    var content = new StringContent("{ \"key\": \"value\" }", System.Text.Encoding.UTF8, "application/json");
    
    // Send the POST request to the API endpoint
    HttpResponseMessage response = await client.PostAsync("/endpoint", content);
    
    // Check if the request was successful
    if (response.IsSuccessStatusCode)
    {
    // Handle the successful response
    string responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine("Response: "   responseBody);
    }
    else
    {
    // Handle the error response
    Console.WriteLine("Error: "   response.StatusCode);
    }

    create an instance of HttpClient, set the base address of the API, and specify the content to be sent in the request body. Then, we use the PostAsync method to send the POST request to the desired endpoint. Finally, we handle the response by checking the IsSuccessStatusCode property and reading the response body if the request was successful.

  • Suggested answer
    RaviKashyap Profile Picture
    RaviKashyap 55,410 on at
    RE: How can i consume rest api of https kind for POST request in c#

    Hi Shazaz,

    You can try the below code which I have used to connect to third party. However I generaly try to access the api from a tool like restclient, postman to confirm the functioning of the api. Sometimes the issue is with the endpoint and we spent time troubleshooting our code.

    ** Do note that headers/ parameters are dependent on the endpoints so you need to change it accordingly.

    ===========

    var resource = "/v1/lodging/semantic/concepts";

               var client = new RestClient("http://connect.reviewpro.com");

               client.Proxy = WebRequest.DefaultWebProxy;

               client.AddHandler("application/json", new JsonDeserializer());

               var request = new RestRequest(resource, Method.GET);

               request.RequestFormat = DataFormat.Json;

               request.AddQueryParameter("api_key", apiKey);

               request.AddQueryParameter("sig", signature);

               // Custum query paramters

               request.AddQueryParameter("lang", "en");

               // execute the request

               IRestResponse response = client.Execute(request);

               var results = ConvertJSonToObject<List<SemanticsConceptSet>>((string)response.Content);

    ==============

    Hope this helps.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: How can i consume rest api of https kind for POST request in c#

    void CallPostMethod(JArray jarray)

           {

               // Restful service URL

               /*string url = */

    //consuming third party service need to send data in json and retrieve rsponse, error coming when response coming.

              string url = "test.slutions.com/.../verbatim&quot;;

               // declare ascii encoding

              // ASCIIEncoding encoding = new ASCIIEncoding();

              Encoding encoding = new UTF8Encoding();

               string strResult = string.Empty;

               // sample xml sent to Service & this data is sent in POST

               //string SampleXml = "SHAHZEB";

               JArray jr= jarray;

               //string postData = jr.ToString();

               Console.WriteLine(jr);

               // convert xmlstring to byte using ascii encoding

               byte[] data = encoding.GetBytes(jr.ToString());

               //string data = jr.ToString();

               // declare httpwebrequet wrt url defined above

               string data11="Shahzeb";

               HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);

               // set method as post

               webrequest.Method = "POST";

               // set content type

               webrequest.Headers.Add("apikey", "PVR1234");

               webrequest.ContentLength = data.Length;

               // get stream data out of webrequest object

               Stream newStream = webrequest.GetRequestStream();

               newStream.Write(data, 0, data.Length);

               newStream.Close();

               // declare & read response from service

               HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();  //error on this line when getting response, 401 error

               //webresponse.Headers.Add("apikey", "1234");

               // set utf8 encoding

               string s = webresponse.ToString();

               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

               strResult = loResponseStream.ReadToEnd();

               Console.WriteLine(strResult);

               Console.ReadKey();

               // close the stream object

               loResponseStream.Close();

               // close the response object

               webresponse.Close();

               // below steps remove unwanted data from response string

               strResult = strResult.Replace("</string>", "");

               strResult = strResult.Substring(strResult.LastIndexOf(strResult));

               Console.WriteLine(strResult);

               Console.ReadKey();  

               }

  • Suggested answer
    Emre GULCAN Profile Picture
    Emre GULCAN 2,379 on at
    RE: How can i consume rest api of https kind for POST request in c#

    Hi,

    You can basically use System.Net.WebRequest to POST your data and get response and also please check RestSharp (http://restsharp.org/) library that can helps you to use RESTful APIs with C# 

    WebRequest webRequest = WebRequest.Create($"{_baseUrl}{request.Endpoint}");
    webRequest.Method = "POST";
    webRequest.ContentType = "application/json";
    
    StreamWriter writer = new StreamWriter(webRequest.GetRequestStream());
    writer.WriteLine(JsonConvert.SerializeObject(YOUR_REQUEST_OBJECT_TO_POST));
    writer.Close();
    WebResponse webResponse = webRequest.GetResponse();
    
    StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());
    var serviceResponse = streamReader.ReadToEnd();
    streamReader.Close();
    


    and of course you need to deserialize your "serviceResponse" to your .NET class like below;

    var deserializedData = JsonConvert.DeserializeObject<YOUR_RESPONSE_CLASS>(serviceResponse);


  • Suggested answer
    CRMISKEY Profile Picture
    CRMISKEY 180 on at
    RE: How can i consume rest api of https kind for POST request in c#

    Please refer restsharp libraries, just a few lines of code and you will be done. you can build RestClient using RestSharp libraries.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,431 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,503 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans