Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

ABAP if_http_client

edgar_almonte
Participant
0 Kudos

hello , i am trying to emulate this python code in abap , but without luck:

def _convert_result(result):  # pragma: no cover
    """Translate SOAP result entries into dictionaries."""
    translation = {
        'NOMBRE': 'name',
        'COMPROBANTE': 'proof',
        'ES_VALIDO': 'is_valid',
        'MENSAJE_VALIDACION': 'validation_message',
        'RNC': 'rnc',
        'NCF': 'ncf',
        u'RNC/Cédula': 'rnc',
        u'Nombre/Razón Social': 'name',
        'Estado': 'status',
        'Tipo de comprobante': 'type',
    }
    return dict(
        (translation.get(key, key), value)
        for key, value in result.items())

def check_dgii(rnc, ncf, timeout=30):  # pragma: no cover
    """Validate the RNC, NCF combination on using the DGII online web service.

    This uses the validation service run by the the Dirección General de
    Impuestos Internos, the Dominican Republic tax department to check
    whether the combination of RNC and NCF is valid. The timeout is in
    seconds.

    Returns a dict with the following structure::

        {
            'name': 'The registered name',
            'status': 'VIGENTE',
            'type': 'FACTURAS DE CREDITO FISCAL',
            'rnc': '123456789',
            'ncf': 'A020010210100000005',
            'validation_message': 'El NCF digitado es válido.',
        }

    Will return None if the number is invalid or unknown."""
    import requests
    try:
        from bs4 import BeautifulSoup
    except ImportError:
        from BeautifulSoup import BeautifulSoup
   
    
    url = 'https://www.dgii.gov.do/app/WebApps/ConsultasWeb/consultas/ncf.aspx'
    headers = {
        'User-Agent': 'Mozilla/5.0 (python-stdnum)',
    }
    data = {
        "__EVENTVALIDATION": "/wEWBAKh8pDuCgK+9LSUBQLfnOXIDAKErv7SBhjZB34//pbvvJzrbkFCGGPRElcd",
        "__VIEWSTATE": "/wEPDwUJNTM1NDc0MDQ5ZGRCFUYoDcVRgzEntcKfSuvPnC2VhA==",
        "ctl00$cphMain$btnConsultar": "Consultar",
        "ctl00$cphMain$txtNCF": ncf,
        "ctl00$cphMain$txtRNC": rnc,
    }
    print(data)
    result = BeautifulSoup(
        requests.post(url, headers=headers, data=data, timeout=timeout).text)
    results = result.find(id='ctl00_cphMain_pResultado')
    if results:
        data = {
            'validation_message': result.find(id='ctl00_cphMain_lblInformacion').get_text().strip(),
        }
        data.update(zip(
            [x.get_text().strip().rstrip(':') for x in results.find_all('strong')],
            [x.get_text().strip() for x in results.find_all('span')]))
        return _convert_result(data)


print(check_dgii('102619883', 'B0100002500')


i try dif way of pass the correct data to the request but without look , always get a communication error but not clue what exactly is wrong , here is my abap code ( thanks in advance):




*&---------------------------------------------------------------------*

*& Report  Z_ED_PROTO_HTTP_RESQ_PARSE

*&

*&---------------------------------------------------------------------*

*&

*&

*&---------------------------------------------------------------------*



REPORT  z_ed_proto_http_resq_parse.

DATA : lv_value TYPE string.



DATA : lo_http_client TYPE REF TO if_http_client .

DATA : lv_url TYPE string.

DATA : return TYPE string.



DATA : lv_err_string TYPE string ,

       lv_ret_code TYPE sy-subrc .

DATA lv_payload TYPE string.

DATA lv_payload_x TYPE xstring.

DATA: rlength TYPE i.



* Build Url



lv_url = 'https://www.dgii.gov.do/app/WebApps/ConsultasWeb/consultas/ncf.aspx'.





* Create Client

*  call method cl_http_client=>create_by_url

*    exporting

*      url    = lv_url

*    importing

*      client = lo_http_client.

CALL METHOD cl_http_client=>create

  EXPORTING

    host               = lv_url

*   service            =

*   proxy_host         =

*   proxy_service      =

    scheme             = 2

*   ssl_id             =

*   sap_username       =

*   sap_client         =

  IMPORTING

    client             = lo_http_client

  EXCEPTIONS

    argument_not_found = 1

    plugin_not_active  = 2

    internal_error     = 3

    OTHERS             = 4.

IF sy-subrc <> 0.

* MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

*            WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.







* set method

lo_http_client->request->set_method( 'POST'  ).

lo_http_client->request->set_header_field( name  = '~request_method'

                                           value = 'POST' ).

*    content type

lo_http_client->request->if_http_entity~set_content_type( content_type = 'text/html' ).



* set enconding

* lo_http_CLIENT->REQUEST->IF_HTTP_ENTITY~set_formfield_encoding( CL_HTTP_REQUEST=>IF_HTTP_ENTITY~CO_ENCODING_RAW ).



* set header data



lo_http_client->request->set_header_field(

EXPORTING

  name  = 'User-Agent'

  value = 'Mozilla/5.0 (python-stdnum)'

).



* set payload



TYPES: BEGIN OF ty_data,

       __EVENTVALIDATION type string,

       __VIEWSTATE TYPE string,

       ctl00$cphMain$btnConsultar TYPE string,

       ctl00$cphMain$txtNCF TYPE string,

       ctl00$cphMain$txtRNC TYPE string,

  END OF ty_data.



DATA: ls_data TYPE ty_data,

      lt_data TYPE STANDARD TABLE OF ty_data.





CONCATENATE '{"__EVENTVALIDATION": "/wEWBAKh8pDuCgK+9LSUBQLfnOXIDAKErv7SBhjZB34//pbvvJzrbkFCGGPRElcd", '

             '"__VIEWSTATE": "/wEPDwUJNTM1NDc0MDQ5ZGRCFUYoDcVRgzEntcKfSuvPnC2VhA==", '

             '"ctl00$cphMain$btnConsultar": "Consultar", '

             '"ctl00$cphMain$txtNCF": "B0100012171", '

             '"ctl00$cphMain$txtRNC": "101064714" }' INTO lv_payload.



ls_data-__eventvalidation = '/wEWBAKh8pDuCgK+9LSUBQLfnOXIDAKErv7SBhjZB34//pbvvJzrbkFCGGPRElcd'.

ls_data-__viewstate = '/wEPDwUJNTM1NDc0MDQ5ZGRCFUYoDcVRgzEntcKfSuvPnC2VhA=='.

ls_data-ctl00$cphMain$btnConsultar = 'Consultar'.

ls_data-ctl00$cphMain$txtNCF = 'B0100002500'.

ls_data-ctl00$cphMain$txtRNC = '102619883'.

APPEND ls_data to lt_data.

CLEAR ls_data.



DATA lcl_writer TYPE REF TO cl_sxml_string_writer.

DATA l_string_json type string.



lcl_writer  = cl_sxml_string_writer=>create( if_sxml=>co_xt_json ).

*lcl_writer = cl_sxml_string_writer=>create( if_sxml=>co_xt_json ).

 CALL TRANSFORMATION id SOURCE text = lt_data  RESULT XML lcl_writer.

 l_string_json = cl_abap_codepage=>convert_from( lcl_writer->get_output( ) ).





cl_demo_output=>write_json(  l_string_json ).



REPLACE ALL OCCURRENCES OF '"' IN lv_payload WITH ''''. ".



CALL FUNCTION 'SCMS_STRING_TO_XSTRING'

  EXPORTING

    text     = lv_payload

*   MIMETYPE = ' '

*   ENCODING =

  IMPORTING

    buffer   = lv_payload_x

  EXCEPTIONS

    failed   = 1

    OTHERS   = 2.

IF sy-subrc <> 0.

* Implement suitable error handling here

ENDIF.

BREAK-POINT.

*rlength = strlen( l_xstring_json ) .



lo_http_client->request->set_cdata(

  EXPORTING

    data   = lv_payload

*    offset = 0

*    length = rlength

)..





* Send

*BREAK-POINT.

*lo_http_client->request->set_form_field( name = '__EVENTVALIDATION' value = '/wEWBAKh8pDuCgK+9LSUBQLfnOXIDAKErv7SBhjZB34//pbvvJzrbkFCGGPRElcd').

*lo_http_client->request->set_form_field( name = '__VIEWSTATE' value = '/wEPDwUJNTM1NDc0MDQ5ZGRCFUYoDcVRgzEntcKfSuvPnC2VhA==').

*lo_http_client->request->set_form_field( name = 'ctl00$cphMain$btnConsultar' value = 'Consultar').

*lo_http_client->request->set_form_field( name = 'ctl00$cphMain$txtNCF' value = 'B0100002500').

*lo_http_client->request->set_form_field( name = 'ctl00$cphMain$txtRNC' value = '102619883').





lo_http_client->send(

*  EXPORTING

*    timeout                    = CO_TIMEOUT_DEFAULT

  EXCEPTIONS

    http_communication_failure = 1

    http_invalid_state         = 2

    http_processing_failed     = 3

    http_invalid_timeout       = 4

    OTHERS                     = 5

).

IF sy-subrc <> 0.

* MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

*            WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

  BREAK-POINT.

ENDIF.

DATA: lv_subrc TYPE sy-subrc.

* Receive

lo_http_client->receive(

  EXCEPTIONS

    http_communication_failure = 1

    http_invalid_state         = 2

    http_processing_failed     = 3

    OTHERS                     = 4

).

IF sy-subrc <> 0.

  lv_subrc = sy-subrc.

  BREAK-POINT.

* MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

*            WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

    lo_http_client->get_last_error(  IMPORTING code = lv_subrc message = lv_err_string ).

  lo_http_client->response->get_status(

    IMPORTING

      code   = lv_ret_code

      reason = lv_err_string

         ).

  MESSAGE lv_err_string TYPE 'I'.

ELSE.

  BREAK-POINT.

ENDIF.







* Now we have the response , parse , display

* do what you like

return = lo_http_client->response->get_cdata( ).
6 REPLIES 6

konstantin_anikeev
Active Contributor

Just an idea. You trying to call https://www.dgii.gov.do

Have you istalled Certificate of www.dgii.gov.do into your SAP System and made it trusted?

Best Regards
Konstantin

0 Kudos

as you can see the or run the python code the certicate is not necesary and in theory what the module of python "requests" do is the same as if_http_client do in abap.

thanks for taking time to answer.

Edgar Almonte With ABAP Web Application Server you must trust the certificates -> download them and install them via transaction STRUST. As you currently use a direct URL, you should install it in the Client anonymous node. In the future you should better configure the URL in transaction SM59 (remote connections) and do the access via this destination (CL_HTTP_CLIENT=>CREATE_BY_DESTINATION).

edgar_almonte
Participant
0 Kudos
sandra.rossi

thanks , that look like it's my problem , the strust tcode show me everything in red , and none ssl client is config , thanks

0 Kudos

Please use the COMMENT button for comments, questions, adding details, etc., ANSWER is only to propose a solution, dixit SAP text at the right of the answer area: "Before answering You should only submit an answer when you are proposing a solution to the poster's problem"

0 Kudos

Nothing is setup? Ask your administrator to setup SSL. He may refer to note 510007 - Setting up SSL on Web Application Server ABAP