Показать сообщение отдельно
Старый 08.06.2022, 09:48   #8  
DarkSpirit22 is offline
DarkSpirit22
Участник
Аватар для DarkSpirit22
 
13 / 76 (3) ++++
Регистрация: 07.11.2013
Адрес: СПб
Я сделал axapta-vs-c# проект WebRequestNet с оберткой:
X++:
using System;
using System.Net;

namespace WebRequestNet
{
    public class HttpWebRequestExceptionSafe
    {
        public HttpWebRequest HttpWebRequest { get; private set; }
        protected HttpWebRequestExceptionSafe(HttpWebRequest _httpWebRequest)
        {
            this.HttpWebRequest = _httpWebRequest;
        }

        public static HttpWebRequestExceptionSafe Create(Uri requestUri)
        {
            return new HttpWebRequestExceptionSafe((HttpWebRequest)HttpWebRequest.Create(requestUri));
        }

        public static HttpWebRequestExceptionSafe Create(string requestUriString)
        {
            return new HttpWebRequestExceptionSafe((HttpWebRequest)HttpWebRequest.Create(requestUriString));
        }

        public HttpWebResponse GetResponseSafe()
        {
            try
            {
                return this.HttpWebRequest.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                HttpWebResponse response = ex.Response as System.Net.HttpWebResponse;

                if (response == null)
                    throw;

                return response;
            }
        }
    }
}
И на примере метода RetailCommonWebAPI.getResponse это будет выглядеть так:

X++:
/// <summary>
/// Get retail web access request.
/// </summary>
/// <param name="_request">
/// Retail web request.
/// </param>
/// <returns>
/// Web response to access.
/// </returns>
public RetailWebResponse getResponse(RetailWebRequest _request)
{
    System.Net.HttpWebRequest       request = null;
    System.Net.HttpWebResponse      response = null;
    CLRObject                       webResponse;
    System.Net.WebHeaderCollection  headers;
    System.IO.MemoryStream          stream;
    Binary                          requestContent;
    str                             responseData;
    System.Exception                ex;
    System.Net.WebException         webException;
    RetailWebResponse               retailWebResponse;
    int                             httpStatusCode;
    str                             contentType;
    MapEnumerator                   headerMapEnumerator;

        //+ Abramov_ 26.04.2022 TSK0000262_02
    WebRequestNet.HttpWebRequestExceptionSafe requestAdapter;
    str                                       exceptionMessage;
    System.Exception                          innerException;
    System.Net.WebExceptionStatus             webExceptionStatus;
    //- Abramov_ 26.04.2022 TSK0000262_02
    ;

    try
    {
        //+ Abramov_ 20.04.2022 TSK0000262_02
        //request = System.Net.WebRequest::Create(_request.parmUrl()) as System.Net.HttpWebRequest;
        requestAdapter = WebRequestNet.HttpWebRequestExceptionSafe::Create(_request.parmUrl());
        request        = requestAdapter.get_HttpWebRequest();
        //- Abramov_ 20.04.2022 TSK0000262_02

        if (strLen(_request.parmMethod()) > 0)
        {
            request.set_Method(_request.parmMethod());
        }

        headers = request.get_Headers();
        //+ Abramov_ 19.11.2021 TSK0000009_01
        /*
        if (strLen(_request.parmHeader()) > 0)
        {
            headers.Add(_request.parmHeader());
        }
        */
        headerMapEnumerator = _request.getHeaders().getEnumerator();
        while (headerMapEnumerator.moveNext())
        {
            headers.Add(any2str(headerMapEnumerator.currentKey()), any2str(headerMapEnumerator.currentValue()));
        }
        //- Abramov_ 19.11.2021 TSK0000009_01

        if (strLen(_request.parmContentType()) > 0)
        {
            request.set_ContentType(_request.parmContentType());
        }

        requestContent = _request.parmContent();
        if (requestContent)
        {
            stream = requestContent.getMemoryStream();
            RetailCommonWebAPI::writeRequestData(request, stream.ToArray());
        }

        //+ Abramov_ 19.11.2021 TSK0000009_01
        if (_request.parmKeepAlive())
            request.set_KeepAlive(CLRInterop::getObjectForAnyType(_request.parmKeepAlive()));
        //- Abramov_ 19.11.2021 TSK0000009_01

        //+ Abramov_ 25.04.2022 TSK0000264_01
        if (_request.parmTimeout())
            request.set_Timeout(_request.parmTimeout());
        //- Abramov_ 25.04.2022 TSK0000264_01

        //+ Abramov_ 20.04.2022 TSK0000262_02
        // Вызов "безопасной" версии метода GetResponse, который не генерирует исключение при получении ответа от сервера, но с кодом отличным от 200.
        /*
        webResponse = request.GetResponse();
        response = webResponse as System.Net.HttpWebResponse;
        */
        response = requestAdapter.GetResponseSafe();
        //- Abramov_ 20.04.2022 TSK0000262_02
    }
    catch (Exception::CLRError)
    {
        ex = ClrInterop::getLastException();

        if (ex != null && ex.get_InnerException() != null)
        {
            innerException = ex.get_InnerException();

            if (innerException is System.Net.WebException)
            {
                webException = innerException as System.Net.WebException;

                //+ Abramov_ 26.04.2022 TSK0000262_02
                //Обработка случая, когда Response "сидит" в WebException, находится в методе requestAdapter.GetResponseSafe();

                webExceptionStatus = webException.get_Status();
                if (webExceptionStatus == System.Net.WebExceptionStatus::Timeout)
                {
                    error(innerException.get_Message());
                    throw Exception::Timeout;
                }
                else
                {
                        throw error(innerException.get_Message());
                }
                //- Abramov_ 26.04.2022 TSK0000262_02
            }
        }

        //+ Abramov_ 26.04.2022 TSK0000262_02
        innerException = ex.get_InnerException();

        while (innerException)
        {
            // BP deviation documented
            if (exceptionMessage)
                exceptionMessage += '\n';

            exceptionMessage += exceptionMessage + " " + CLRInterop::getAnyTypeForObject(innerException.get_Message());
            innerException = innerException.get_InnerException();
        }

        throw error(exceptionMessage);
        //- Abramov_ 26.04.2022 TSK0000262_02
    }

    responseData = RetailCommonWebAPI::readResponseData(response);
    response.Close();

    httpStatusCode = response.get_StatusCode();

    contentType = response.get_ContentType();
    retailWebResponse = new RetailWebResponse(httpStatusCode, responseData, contentType);

    return retailWebResponse;
}