ABAP调用restfull webservice实例

下面示例的环境为:S/4 HANA 1809

调用的webservice为使用python3的三方库ladon编写的restful风格的webservice

*&---------------------------------------------------------------------*
*& Report ZTEST003
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT ztest003.

DATA:
  http_client      TYPE REF TO if_http_client,
  rest_http_client TYPE REF TO cl_rest_http_client,
  url              TYPE string VALUE `http://192.168.0.102:8080/Calculator/jsonwsp`.
DATA:payload TYPE string VALUE `{"type":"jsonwsp/request","version":"1.0","methodname":"add","args":{"a":"3","b":"9"}}`.


* 通过url创建一个http客户端对象
CALL METHOD cl_http_client=>create_by_url
  EXPORTING
    url                = url
*   proxy_host         =
*   proxy_service      =
*   ssl_id             =
*   sap_username       =
*   sap_client         =
*   proxy_user         =
*   proxy_passwd       =
*   do_not_use_client_cert = ABAP_FALSE
  IMPORTING
    client             = http_client
  EXCEPTIONS
    argument_not_found = 1
    plugin_not_active  = 2
    internal_error     = 3
    OTHERS             = 4.
IF sy-subrc <> 0.
* Implement suitable error handling here
ENDIF.

*获取授权
*http_client->authenticate( username = 'User001' password = 'Password' ).

*创建rest客户端实例
rest_http_client = NEW cl_rest_http_client( http_client ).

*创建请求实例
CALL METHOD rest_http_client->if_rest_client~create_request_entity
*  EXPORTING
*    iv_multipart = ABAP_FALSE
  RECEIVING
    ro_entity = DATA(rest_request).
*设置请求类型
CALL METHOD rest_request->set_content_type
  EXPORTING
    iv_media_type = if_rest_media_type=>gc_appl_json
*   it_parameter  =
  .
*设置消息内容
CALL METHOD rest_request->set_string_data
  EXPORTING
    iv_data = payload.

*提交请求
CALL METHOD rest_http_client->if_rest_resource~post
  EXPORTING
    io_entity = rest_request.

*获取请求响应数据对象
CALL METHOD rest_http_client->if_rest_client~get_response_entity
  RECEIVING
    ro_response_entity = DATA(rest_response).

*获取响应抬头信息
*DATA(lv_status) = rest_response->get_header_field( '~status_code' ). "#EC NEEDED
*DATA(lv_reason) = rest_response->get_header_field( '~status_reason' ). "#EC NEEDED
*DATA(lv_content_length) = rest_response->get_header_field( 'content-length' ). "#EC NEEDED
*DATA(lv_location) = rest_response->get_header_field( 'location' ). "#EC NEEDED
*DATA(lv_content_type) = rest_response->get_header_field( 'content-type' ). "#EC NEEDED

CALL METHOD rest_response->get_header_fields
  RECEIVING
    rt_header_fields = DATA(rest_response_headers).

*获取响应内容信息
CALL METHOD rest_response->get_string_data
  RECEIVING
    rv_data = DATA(rest_response_data).

*关闭客户端

http_client->close( ).

WRITE rest_response_data.

 主要用到的几个类:

  • cl_http_client
  • cl_rest_http_client

核心的接口:

  • IF_HTTP_CLIENT
  • IF_REST_CLIENT
  • IF_REST_ENTITY
  • IF_REST_MEDIA_TYPE

 

posted @ 2022-08-11 10:38  荒野游侠  阅读(251)  评论(0编辑  收藏  举报