Sample Code

External HTTP Call from ABAP Program

In order to make a successful call, you need to do the following:

  1. Set proper credentials and URL for the call.
  2. Choose the method based on the API you are about to call
  3. Set data for the call

In this example, we are using RFC Connection information for credentials and URL information. This is better than hardcoding user credentials and url in the program.


        Data: lv_dest         TYPE rfcdes-rfcdest,
              lo_client       TYPE REF TO if_http_client.

      CALL METHOD cl_http_client=>create_by_destination
        EXPORTING
          destination              = lv_dest
    "RFC Destination in SAP
        IMPORTING
          client                   = lo_client
        EXCEPTIONS
          argument_not_found       = 1
          destination_not_found    = 2
          destination_no_authority = 3
          plugin_not_active        = 4
          internal_error           = 5
          OTHERS                   = 6.

Alternative way is to create url and set credentials in the program itself. To be used only if RFC destination is not available.


* Set the content type: for example JSON or XML
      CALL METHOD lo_client->request->set_content_type('application/xml').
     
* Set the method: For example POST, GET, PUT
      CALL METHOD lo_client->request->set_method('POST').

* Set the data: Two method are availabe for setting the data.
* Using CDATA as data is character type
      CALL METHOD lo_client->request->set_cdata
        EXPORTING
          data = lv_xml_data.

* Make the call
      CALL METHOD lo_client->send
*     exporting  timeout = lc_timeout
        EXCEPTIONS
          http_communication_failure = 1
          http_invalid_state         = 2
          http_processing_failed     = 3
          OTHERS                     = 4.

* Receive status
      CALL METHOD lo_client->receive
        EXCEPTIONS
          http_communication_failure = 1
          http_invalid_state         = 2
          http_processing_failed     = 3
          OTHERS                     = 4.
      IF sy-subrc <> 0.

* Get the last error
        CALL METHOD lo_client->get_last_error
          IMPORTING
            code    = lv_subrc
            message = lv_errortext.

      ENDIF.

* Close the connection.
      CALL METHOD lo_client->close
        EXCEPTIONS
          http_invalid_state = 1
          OTHERS             = 2.

Remember, this is not a fully working program. Please add relevant details and fill up the variables as required.

Let us know whether it works or if you get stuck.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)

Follow by Email
Twitter
LinkedIn
LinkedIn
Share