一、SE24创建类:Z_HCX_HTTP
1、创建类:
2、切换到接口(interface)页签,输入IF_HTTP_EXTENSION ,回车。切换到方法(method)页签,双击IF_HTTP_EXTENSION~HANDLE_REQUEST进入代码编辑界面。
在IF_HTTP_EXTENSION~HANDLE_REQUEST方法编写代码:
METHOD if_http_extension~handle_request.
DATA: BEGIN OF ls_data,
matnr TYPE matnr,
maktx TYPE maktx,
END OF ls_data.
DATA: lt_data LIKE TABLE OF ls_data.
DATA: lt_fields TYPE tihttpnvp.
FIELD-SYMBOLS: <fs_field> LIKE LINE OF lt_fields.
DATA: lv_method TYPE string. "获取GET/POST方式
DATA: lv_json TYPE string, "返回参数
lv_json1 TYPE string, "获取传回值数据
lv_json2 TYPE string. "获取传回值数据
* 获取JSON抬头数据
server->request->get_header_fields(
CHANGING
fields = lt_fields
).
lv_method = server->request->get_header_field( name = '~request_method' )."获取GET/POST方式
CALL METHOD server->response->if_http_entity~set_content_type
EXPORTING
content_type = 'application/json'.
CASE lv_method.
WHEN 'GET'.
* 获取数据
SELECT matnr maktx INTO CORRESPONDING FIELDS OF TABLE lt_data
FROM makt
UP TO 20 ROWS.
* 内表转换JSON
CALL METHOD /ui2/cl_json=>serialize
EXPORTING
data = lt_data
RECEIVING
r_json = lv_json.
* 将行数据JSON返回给调用端
server->response->set_cdata(
EXPORTING
data = lv_json
).
server->response->set_status( code = 200 reason = 'OK' ).
WHEN 'POST'.
* 获取JSON行数据
lv_json1 = server->request->if_http_entity~get_cdata( ).
* 解析json至内表方法1
/ui2/cl_json=>deserialize( EXPORTING json = lv_json1
CHANGING data = ls_data ).
IF NOT lv_json1 IS INITIAL.
* 获取数据
SELECT matnr maktx INTO CORRESPONDING FIELDS OF TABLE lt_data
FROM makt
UP TO 20 ROWS
where matnr = ls_data-matnr.
* 内表转换json
CALL METHOD /ui2/cl_json=>serialize
EXPORTING
data = lt_data
RECEIVING
r_json = lv_json.
* 将行数据JSON返回给调用端
server->response->set_cdata(
EXPORTING
data = lv_json
).
ENDIF.
LOOP AT lt_fields INTO DATA(ls_fields).
CASE ls_fields-name.
WHEN 'lt_data'.
lv_json2 = ls_fields-value.
ENDCASE.
ENDLOOP.
* 解析json至内表方法1
/ui2/cl_json=>deserialize( EXPORTING json = lv_json2
CHANGING data = lt_data ).
IF NOT lv_json2 IS INITIAL.
* 将行数据JSON返回给调用端
server->response->set_cdata(
EXPORTING
data = 'SoapUi传参已收到'
).
ENDIF.
server->response->set_status( code = 200 reason = 'OK' ).
ENDCASE.
ENDMETHOD.
二、使用事务码?SICF?在?default_host/sap?节点下面创建子节点,用?Z_HCX_HTTP?类并激活方法:
1、创建子元素:
之后点击保存。
2、在default_host/sap中找到刚刚创建的子元素:Z_HCX_HTTP激活服务:
3、获取URL调用地址:
直接打开默认是GET请求:
但是像企业微信这样的第三方访问时,该URL不是真正的URL,找BASIS要URL。
在Postman 中测试post请求:
在SoapUI 中测试post请求:
|