Friday, July 24, 2015

External Service call (Web access) from a CRM plug-in Post data and get respnse- CRM Dynamics 2015 / 2013 /2011


Call external web service from CRM Dynamics. Post data and get response object.

var url = "https://postdataurl";
            var pairs = new NameValueCollection()
                       {
                           { "Email", "vikram@test.com" },
                           { "FirstName", "Vikram" },
                           { "InventoryId", "1" },
                       };
            byte[] response = null;
            using (WebClient client = new WebClient())
            {
                response = client.UploadValues(url, "POST", pairs); //Adding post message as input is optional
            }
            var text = System.Text.Encoding.UTF8.GetString(response);


            /*  Equivalent to following Webrequest/ json Call */
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"Email\":\"" + "vikram@test.com" + "\"," +
                    "\"FirstName\":\"" + "Vikram" + "\"," +
                    "\"InventoryId\":" + 3 + "," +
                    "\"bypassCRM\":\"true\"}";
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    text = streamReader.ReadToEnd();
                }
            }
            /* Equivalant Webrequest/ json Call */

         


No comments: