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

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

(0) ShareShare
ReportReport
Posted on by 184

HI All,

I am facing an issue while calling sending a request to API.

Below is the error message.

Microsoft.Dynamics.Ax.Xpp.ErrorException: 'The request was aborted: The connection was closed unexpectedly.'

using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;

public class WTL_6DeePaymentAPIservice
{
   public static void postPaymentAPI()
   {

       str                  _profileGUID =  "3ace35c3-6443-eb11-a812-000d3a20f116";
       str                 _transactionID = "12323553434";
       str                 _amount = "25.00";
       WTL_PaymentMode     _paymentMode = "1";
       str                _accountID = "1000107754";
       WTL_TransactionCurrencyID   _currencyCode = "QAR";
       WTL_AccountName     _customerName = "Harryson Jerico";
       str                 _amountPaid = "25";
       str                 _externalID = "4520941365";
       str                 _cardHolderName = "Patrisia Allen";
       str                 _modelValue = "113cvxrdu1";
       str                 _modelKey = "sample_key";
       str                 _paymentGWtoken = "vsE0aZWzPq02376";
       str                 _comment = "order payment";
       str                 _authToken = "xrzy6ryymust";
       str                 _orderType = "MakePayment";
       str                 _id = "";
       str                 _value = "";
        str                 _contactNumber = "(555) 555-1234";

        
        System.Exception                ex;
       

        try
        {
            JObject jObject = JObject::parse(WTL_6DeeAPITokenSerice::getToken());
            WebHeaderCollection httpHeaders = new WebHeaderCollection();
            httpHeaders.Add("Authorization", "Bearer "   strFmt("%1",jObject.SelectToken("$.access_token")));
            httpHeaders.Add("requestid", "7777777");
            httpHeaders.Add("sourcenode", "ERP");
            httpHeaders.Add("requesttimestamp", "2022-09-12");

            HttpWebRequest request = System.Net.WebRequest::Create("API URL");
    
            request.Headers = httpHeaders;
            request.Method = "POST";
            request.ContentType = "application/json";

            str json = WTL_6DJSONserializer::serializeJSON(
                                                            _profileGUID,
                                                            _transactionID,
                                                            strFmt("%1",_amount),
                                                            _paymentMode,
                                                            _accountID,
                                                            _currencyCode,
                                                            _customerName,
                                                            strFmt("%1",_amountPaid),
                                                            _externalID,
                                                            _cardHolderName,
                                                            _modelValue,
                                                            _modelKey,
                                                            _paymentGWtoken,
                                                            _comment,
                                                            _authToken,
                                                            _orderType,
                                                            _id,
                                                            _value,
                                                            _contactNumber);

            using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                System.Byte[] postBytes;
                System.Text.Encoding encoding = System.Text.Encoding::get_ASCII();
                postBytes = encoding.GetBytes(json);
                streamWriter.Write(postBytes); // writing JSON

                using (System.Net.HttpWebResponse response = request.GetResponse())
                {
                    StreamReader streamRead = new StreamReader(response.GetResponseStream());
                    info(streamRead.ReadToEnd());
                }
            }

        }
        catch (ex)
        {
            throw error(ex.Message);
        }
        //catch (Exception::CLRError)
        //{
        //    throw error(AifUtil::getClrErrorMessage());
        //}
    }

}

I have pasted my whole code.

And while debugging I have found that the exception is thrown at " using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream())) "

Please help me to understand this issue and fix it

I have the same question (0)
  • D365_Wibes Profile Picture
    184 on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    Thanks a lot for your help Martin in this.

    The issue was with the APIM Inspector trace. MY VM's IP was blocked there and allowing it then every went through as expected.

  • D365_Wibes Profile Picture
    184 on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    Totally Agree Martin, but unfortunately stuck in a very less time line. That's why going through like this.

    Actually I am getting error at line exactly s below:

    using (System.Net.HttpWebResponse response = request.GetResponse())

    When I have analysed the exception details I could see the message 400 bad request .....  along with I have also noticed that is there a status as "Protocol Error"

  • Verified answer
    Martin Dráb Profile Picture
    236,192 Most Valuable Professional on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    Not much. First of all, read the documentation of the web service that you want to call. Sometimes there is a test version, which might make things easier.

    Forget code and your real data for a moment and create a minimal message for testing. Often you can copy an example from documentation. Run it in Postman. When you get it working, you can start adding complexity.

    Trying to write a complex solution before you don't have the basics running is usually a bad idea.

  • D365_Wibes Profile Picture
    184 on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    Hi Marin,

    Can you please suggest me some thing based on the details I have shared if possible please?

  • D365_Wibes Profile Picture
    184 on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    In if you can guess something from the details that I shared with you  please let me know .

    Even I am trying to figure but it is looking very hard to me

  • D365_Wibes Profile Picture
    184 on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    using Newtonsoft.Json.JsonTextWriter;
    public class WTL_6DJSONserializer
    {
        public static str serializeJSON(str                 _profileGUID,
                                        str                 _transactionID,
                                        str                 _amount,
                                        WTL_PaymentMode     _paymentMode,
                                        str                _accountID,
                                        WTL_TransactionCurrencyID   _currencyCode,
                                        WTL_AccountName     _customerName,
                                        str                 _amountPaid,
                                        str                 _externalID,
                                        str                 _cardHolderName,
                                        str                 _modelValue,
                                        str                 _modelKey,
                                        str                 _paymentGWtoken,
                                        str                 _comment,
                                        str                 _authToken,
                                        str                 _orderType,
                                        str                 _id,
                                        str                 _value,
                                        str                 _contactNumber)
        {
            //WTL_6deeParmsContract contract = new WTL_6DeeParmsContract();
    
            //contract.parmProfileID(_profileGUID);
            //contract.parmTransactionID(_transactionID);
            //contract.parmAmount(_amount);
            //contract.parmPaymentMode(_paymentMode);
            //contract.parmAccountID(_accountID);
            //contract.parmCurrencyCode(_currencyCode);
            //contract.parmCustName(_customerName);
            //contract.parmAmountPaid(_amountPaid);
            //contract.parmExternalID(_externalID);
            //contract.parmCardHolderName(_cardHolderName);
            //contract.parmModelValue(_modelValue);
            //contract.parmModelKey(_modelKey);
            //contract.parmPaymentGWtoken(_paymentGWtoken);
            //contract.parmComment(_comment);
            //contract.parmAuthToken(_authToken);
            //contract.parmOrderType(_orderType);
            ////contract.parmId(_id);
            ////contract.parmValue(_value);
            //contract.parmContactNumber(_contactNumber);
    
            //str sFormJSONserializer = FormJsonSerializer::serializeClass(contract);
    
            //return "order_information:"   '"'   sFormJSONserializer   '"';
    
            System.IO.StringWriter          stringWriter;
            Newtonsoft.Json.JsonTextWriter  jsonWriter;
    
            stringWriter = new System.IO.StringWriter();
            jsonWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter);
    
            str sJSON = "";
    
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("order_information");
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("payment");
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("ext_profile_id");
            jsonWriter.WriteValue("4dcea503-a366-eb11-a812-000d3abb5370");
            jsonWriter.WritePropertyName("transaction_id");
            jsonWriter.WriteValue("12323553434");
            jsonWriter.WritePropertyName("amount");
            jsonWriter.writeValue("25.00");
            jsonWriter.WritePropertyName("payment_detail");
            jsonWriter.WriteStartArray();
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("payment_mode");
            jsonWriter.WriteValue("1");
            jsonWriter.WritePropertyName("amount_paid");
            jsonWriter.WriteValue("25");
            jsonWriter.WritePropertyName("reference_external_id");
            jsonWriter.WriteValue("4520941365");
            jsonWriter.WritePropertyName("card_holder_name");
            jsonWriter.WriteValue("Patrisia Allen");
            jsonWriter.WritePropertyName("mode_detail");
            jsonWriter.WriteStartArray();
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("value");
            jsonWriter.WriteValue("113cvxrdu1");
            jsonWriter.WritePropertyName("key");
            jsonWriter.WriteValue("sample_key");
            jsonWriter.WriteEndObject();
            jsonWriter.WriteEndArray();
            jsonWriter.WriteEndObject();
            jsonWriter.WriteEndArray();
            jsonWriter.WritePropertyName("accound_id");
            jsonWriter.WriteValue("1000384111");
            jsonWriter.WritePropertyName("payment_gw_token");
            jsonWriter.WriteValue("vsE0aZWzPq02376");
            jsonWriter.WritePropertyName("comment");
            jsonWriter.WriteValue("order payment");
            jsonWriter.WritePropertyName("auth_token");
            jsonWriter.WriteValue("xrzy6ryymust");
            jsonWriter.WritePropertyName("currency_code");
            jsonWriter.WriteValue("QAR");
            jsonWriter.WriteEndObject();
            jsonWriter.WritePropertyName("customer_name");
            jsonWriter.WriteValue("Harryson Jerico");
            jsonWriter.WritePropertyName("order_type");
            jsonWriter.WriteValue("MakePayment");
            jsonWriter.WritePropertyName("dataset");
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("param");
            jsonWriter.WriteStartArray();
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("id");
            jsonWriter.WriteValue("");
            jsonWriter.WritePropertyName("value");
            jsonWriter.WriteValue("");
            jsonWriter.WriteEndObject();
            jsonWriter.WriteEndArray();
            jsonWriter.WriteEndObject();
            jsonWriter.WritePropertyName("contact_number");
            jsonWriter.WriteValue("(555) 555-1234");
            jsonWriter.WriteEndObject();
            jsonWriter.WriteEndObject();
    
            sJSON = stringWriter.ToString();
    
            return sJSON;
        }
    
    }

  • D365_Wibes Profile Picture
    184 on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    1s.PNG

    2s.PNG

    using Newtonsoft.Json.Linq;
    using System.Net;
    using System.IO;
    
    public class WTL_6DeePaymentAPIservice
    {
       public static void postPaymentAPI()
       {
    
           str                  _profileGUID =  "4dcea503-a366-eb11-a812-000d3abb5370";
            str                 _transactionID = "12323553434";
           str                 _amount = "25.00";
           str                 _paymentMode = "1";
           str                 _accountID = "1000107754";
           str                 _currencyCode = "QAR";
           str                 _customerName = "Harryson Jerico";
           str                 _amountPaid = "25";
           str                 _externalID = "4520941365";
           str                 _cardHolderName = "Patrisia Allen";
           str                 _modelValue = "113cvxrdu1";
           str                 _modelKey = "sample_key";
           str                 _paymentGWtoken = "vsE0aZWzPq02376";
           str                 _comment = "order payment";
           str                 _authToken = "xrzy6ryymust";
           str                 _orderType = "MakePayment";
           str                 _id = "";
           str                 _value = "";
            str                 _contactNumber = "(555) 555-1234";
    
            //System.Net.HttpWebRequest       request;
            //System.Net.HttpWebResponse      response;
            //CLRObject                       clrObj;
            System.Exception                ex;
            //System.Net.WebHeaderCollection  httpHeader;
            //System.IO.Stream                requestStream, responseStream;
            //System.IO.StreamWriter          streamWriter;
    
            try
            {
                JObject jObject = JObject::parse(WTL_6DeeAPITokenSerice::getToken());
                WebHeaderCollection httpHeaders = new WebHeaderCollection();
                httpHeaders.Add("Authorization", "Bearer "   strFmt("%1",jObject.SelectToken("$.access_token")));
                httpHeaders.Add("requestid", "23456765432");
                httpHeaders.Add("sourcenode", "ERP");
                httpHeaders.Add("requesttimestamp", "2022-09-12");
    
                HttpWebRequest request = System.Net.WebRequest::Create("https:// API URL");
                
                request.Headers = httpHeaders;
                request.Method = "POST";
                request.ContentType = "application/json";
                
    
                //webRequest.Headers = httpHeaders;
                //webRequest.Method = "POST";
                //webRequest.ContentType = "application/json";
    
                str json = WTL_6DJSONserializer::serializeJSON(
                                                                _profileGUID,
                                                                _transactionID,
                                                                _amount,
                                                                _paymentMode,
                                                                _accountID,
                                                                _currencyCode,
                                                                _customerName,
                                                                _amountPaid,
                                                                _externalID,
                                                                _cardHolderName,
                                                                _modelValue,
                                                                _modelKey,
                                                                _paymentGWtoken,
                                                                _comment,
                                                                _authToken,
                                                                _orderType,
                                                                _id,
                                                                _value,
                                                                _contactNumber);
    
                //System.Byte[] postBytes;
                //System.Text.Encoding encoding = System.Text.Encoding::get_ASCII();
                //postBytes = encoding.GetBytes(json);
    
                //System.IO.Stream postStream = webRequest.GetRequestStream();
                //postStream.Write(postBytes, 0, postBytes.Length);
                //postStream.Flush();
                //postStream.Close();
    
                //if (webRequest != null)
                //{
                //    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
                //    {
                //        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                //        {
                //            info(sr.ReadToEnd());
                //        }
                //    }
                //}
                //using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream()))
    
                using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    System.Byte[]           byte;
                    str                     str64;
    
                    System.Text.Encoding    encoding = System.Text.Encoding::get_UTF8();
    
                    // UTF8 input
                    byte = encoding.GetBytes(json);
    
                    // base64 Output
                    str64 = System.Convert::ToBase64String(byte);
                    //postBytes = encoding.GetBytes(base64);
                    //streamWriter.Write(postBytes); // writing JSON
                    streamWriter.Write(str64);
                }
                using (System.Net.HttpWebResponse response = request.GetResponse())
                {
                    StreamReader streamRead = new StreamReader(response.GetResponseStream());
                    info(streamRead.ReadToEnd());
                }
                //httpHeader = new System.Net.WebHeaderCollection();
                //new InteropPermission(InteropKind::ClrInterop).assert();
                //request = System.Net.WebRequest::Create("https://api.tst.sqcp.qa/accountmanagement/apiInterface/AccountManagement/MakePayment");
                //////request = clrObj;
                ////// adding headers
                ////JObject jObject = JObject.Parse(WTL_6DeeAPITokenSerice::getToken());
                //httpHeaders.Add("Authorization", "Bearer "   strFmt("%1",jObject.SelectToken("$.access_token")));
                //httpHeader.Add("requestid", "23456765432");
                //httpHeader.Add("sourcenode", "ERP");
                //httpHeader.Add("requesttimestamp", "2022-09-12");
                //request.set_Headers(httpHeader);
                //request.Method = "POST";
                //request.ContentType = "application/json";
                //requestStream = request.GetRequestStream();
                //streamWriter = new System.IO.StreamWriter(request.GetRequestStream());
                //System.Byte[] postBytes;
                //System.Text.Encoding encoding = System.Text.Encoding::get_ASCII();
                ////str sJSON = WTL_6DJSONserializer::serializeJSON(_profileGUID,_transactionID,strFmt("%1",_amount),
                ////                                                       _paymentMode,_accountID,_currencyCode,
                ////                                                       _customerName,strFmt("%1",_amountPaid),
                ////                                                       _externalID,_cardHolderName,_modelValue,_modelKey,
                ////                                                       _paymentGWtoken,_comment,_authToken,_orderType,
                ////                                                       _id,_value,_contactNumber);
                //postBytes = encoding.GetBytes(json);
                //streamWriter.Write(postBytes); // writing JSON
                //streamWriter.Flush();
                //streamWriter.Close();
                //response = request.GetResponse();
                //System.IO.StreamReader streamRead = new System.IO.StreamReader(response.GetResponseStream());
                //info(streamRead.ReadToEnd());
            }
            catch (ex)
            {
                throw error(ex.Message);
            }
            //catch (Exception::CLRError)
            //{
            //    throw error(AifUtil::getClrErrorMessage());
            //}
        }
    
    }

  • Martin Dráb Profile Picture
    236,192 Most Valuable Professional on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    I'm sorry, but I know nothing about the web service you're trying to call, therefore I can't tell you how it should be used.

  • D365_Wibes Profile Picture
    184 on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    Also I have tested the token that is generating via my code in Postman and it got successfully authenticated.

  • D365_Wibes Profile Picture
    184 on at
    RE: Error while calling API 'The request was aborted: The connection was closed unexpectedly.'

    HI Martin,

    I am correctly passing the token.

    Also I have included all the required headers in it.

    What else I would have to check please let me know?

    This is my first API based integration hence struggling a lot

    I am still getting 400 bad request.

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
CA Neeraj Kumar Profile Picture

CA Neeraj Kumar 2,351

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 874 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 638 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans