DATA: lc_http_client TYPE REF TO if_http_client,
LEN TYPE I, "发送报文长度
l_json_data TYPE string,
l_json_string TYPE string,
l_result_data TYPE string,
l_url TYPE string.
DATA lc_json TYPE REF TO cl_fdt_json_serializer. "json格式转换
DATA l_result TYPE ZMSG02.
l_url = 'http://xxx.xxx'. "访问地址
l_json_string = '{"userid":"65509","message":"Hello"}'.
*****创建http服务
CALL METHOD cl_http_client=>create_by_url
EXPORTING
url = l_url
IMPORTING
client = lc_http_client
EXCEPTIONS
argument_not_found = 1
plugin_not_active = 2
internal_error = 3
OTHERS = 4.
IF sy-subrc <> 0.
EXIT.
ENDIF.
*****转换json格式
CREATE OBJECT lc_json.
CALL METHOD lc_json->serialize_int
EXPORTING
data = IS_INPUT
RECEIVING
r_json = l_json_data.
LEN = STRLEN( l_json_data ).
TRANSLATE l_json_data TO LOWER CASE.
"设定传输请求内容格式以及编码格式
CALL METHOD lc_http_client->request->set_header_field
EXPORTING
name = 'Content-Type'
value = 'application/JSON; charset=utf-8'.
CALL METHOD lc_http_client->request->set_method( 'POST' ).
*****设置传入字符串
CALL METHOD lc_http_client->REQUEST->SET_CDATA
EXPORTING
DATA = l_json_data
OFFSET = 0
LENGTH = LEN.
*****发送http服务
CALL METHOD lc_http_client->send
EXCEPTIONS
http_communication_failure = 1
http_invalid_state = 2
http_processing_failed = 3
http_invalid_timeout = 4
OTHERS = 5.
IF sy-subrc <> 0.
" EXIT.
ENDIF.
"接收
CALL METHOD lc_http_client->RECEIVE
EXCEPTIONS
HTTP_COMMUNICATION_FAILURE = 1
HTTP_INVALID_STATE = 2
HTTP_PROCESSING_FAILED = 3.
IF sy-subrc = 0.
ENDIF.
l_result_data = lc_http_client->response->get_cdata( ).
*****解析JSON数据
CALL METHOD lc_json->deserialize_int
EXPORTING
json = l_result_data
CHANGING
data = l_result.
IF sy-subrc = 0.
ES_RET-CODE = l_result-errcode.
ES_RET-MSG = l_result_data.
ENDIF.
|