ABAP接口之Http发送json报文
abap 调用http 发送 json 测试函数
SE11创建结构:zsmlscpnotice
SE37创建函数:zqb_test_http_fuc1
FUNCTION zqb_test_http_fuc1.
*"----------------------------------------------------------------------
*"*"本地接口:
*"----------------------------------------------------------------------
DATA: json_ser TYPE REF TO cl_trex_json_serializer,
json_des TYPE REF TO cl_trex_json_deserializer.
DATA: lv_url TYPE string."http 服务接口地址
DATA: lo_http_client TYPE REF TO if_http_client.
DATA: lv_len TYPE i."发送报文长度
DATA: lv_respon TYPE string.
DATA: lv_subrc TYPE sy-subrc.
DATA: lv_json_str TYPE string. "发送报文
DATA: lv_msgty TYPE c,
lv_msgtx TYPE string.
DATA: lt_json TYPE STANDARD TABLE OF zsmlscpnotice,
ls_json TYPE zsmlscpnotice.
* 设置HTTP接口地址
lv_url = 'http://ip:端口/服务'.
* 设置报文内容(json格式字符串)
ls_json-functionname = 'XXXXXX'.
ls_json-bcpcode = '20170214000000'.
ls_json-status = 'S'.
ls_json-msg = '请调用接口抓取数据'.
ls_json-result = ''.
APPEND ls_json TO lt_json.
* 内表->JSON
CREATE OBJECT json_ser
EXPORTING
data = lt_json[].
CALL METHOD json_ser->serialize.
CALL METHOD json_ser->get_data
RECEIVING
rval = lv_json_str.
"创建客户端请求
CALL METHOD cl_http_client=>create_by_url
EXPORTING
url = lv_url
IMPORTING
client = lo_http_client
EXCEPTIONS
argument_not_found = 1
plugin_not_active = 2
internal_error = 3
OTHERS = 4.
IF sy-subrc <> 0.
"lv_subrc = sy-subrc.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH
sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
EXIT.
ENDIF.
"设定传输请求内容格式以及编码格式
lo_http_client->request->set_content_type( content_type = 'application/json; charset=utf-8' ).
"设定调用服务
lo_http_client->request->set_method( if_http_request=>co_request_method_post ).
"设置待传输内容
lv_len = strlen( lv_json_str ).
CALL METHOD lo_http_client->request->set_cdata
EXPORTING
data = lv_json_str
offset = 0
length = lv_len.
"发送请求
lo_http_client->send( EXCEPTIONS http_communication_failure = 1
http_invalid_state = 2 ).
IF sy-subrc <> 0.
"操作失败,获取失败原因
"lv_subrc = sy-subrc.
lo_http_client->get_last_error( IMPORTING message = lv_msgtx ).
lv_msgty = 'E'.
EXIT.
ENDIF.
"读取远程服务返回的处理过结果。
lo_http_client->receive( EXCEPTIONS http_communication_failure = 1
http_invalid_state = 2
http_processing_failed = 3 ).
IF sy-subrc <> 0 .
"lv_subrc = sy-subrc.
lo_http_client->get_last_error( IMPORTING message = lv_msgtx ).
lv_msgty = 'E'.
EXIT.
ELSE.
"读取返回返回内容
CLEAR lv_respon.
lv_respon = lo_http_client->response->get_cdata( ).
ENDIF.
ENDFUNCTION.