web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Customer Service forum

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

(0) ShareShare
ReportReport
Posted on by

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:
  • Suggested answer
    CRMISKEY Profile Picture
    180 on at

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

  • Suggested answer
    Emre GULCAN Profile Picture
    2,379 on at

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


  • Community Member Profile Picture
    on at

    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
    RaviKashyap Profile Picture
    55,410 Moderator on at

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

               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.

  • nickmanny Profile Picture
    136 on at

    // 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.

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 > Customer Service

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans