CL_HTTP_CLIENT发送Json数据

REPORT zrtest2
       NO STANDARD PAGE HEADING LINE-SIZE 255.

DATA: lo_http_client  TYPE REF TO if_http_client.

DATA: lv_len    TYPE i."发送报文长度
DATA: lv_RESPONSE TYPE string.
DATA: lv_json_str TYPE string. "发送报文
DATA: lv_code     TYPE i.
DATA:lv_url TYPE string,
     lv_username TYPE string,
     lv_password TYPE string,
     lv_content_type TYPE string.

data: lv_msgty type sy-msgty,
      lv_message type string.

DATA: BEGIN OF ls_data,
      text TYPE string,
      END OF ls_data.

ls_data-text = '你好'.

CALL METHOD zcl_json=>serialize
  EXPORTING
    data           = ls_data
    "pretty_name    = iv_pretty_name
    numc_as_string = 'X'
  RECEIVING
    r_json         = lv_json_str.

lv_url = 'url'.
lv_username = 'xxx'.
lv_password = '123'.
*  "创建客户端请求
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_message = '创建http代理出错'.
  lv_msgty = 'E'.
  EXIT.
ENDIF.

"设定传输请求内容格式以及编码格式
IF lv_content_type IS INITIAL.
  lv_content_type = 'application/json; charset=utf-8'.
  lo_http_client->request->set_content_type( content_type = lv_content_type ).
ELSE.
  lo_http_client->request->set_content_type( content_type = lv_content_type ).
ENDIF.

CALL METHOD lo_http_client->request->set_authorization
  EXPORTING
    username = lv_username
    password = lv_password.

"设定调用服务
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.
  "操作失败,获取失败原因
  lo_http_client->get_last_error( IMPORTING message = lv_message ).
  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 .
  lo_http_client->get_last_error( IMPORTING message = lv_message ).
  lv_msgty = 'E'.
  EXIT.
ELSE.
  CALL METHOD lo_http_client->response->get_status
    IMPORTING
      code   = lv_code
      reason = lv_message.
  IF lv_code BETWEEN '200' AND '299'.
*    读取返回内容
    CLEAR lv_response.
    lv_msgty = 'S'.
    lv_response = lo_http_client->response->get_cdata( ).
    lv_message = lv_response.

  ELSE.
    lv_msgty = 'E'.
    lv_message = '失败'.
  ENDIF.
ENDIF.
write: lv_msgty , lv_message.

你可能感兴趣的:(SAP,http,json,abap)