ABAP 调用外部接口详解编程语言

1、JSON转换 
DATA: json_ser TYPE REF TO cl_trex_json_serializer. 
 
2、http客户端访问 
DATA: lo_http_client  TYPE REF TO if_http_client. 
 
3、定义传入参数结构 
{ 
    head:... 
    detail:[ 
        xxx:xxx. 
    ] 
} 
 
4、定义接收参数结构 
 
5、定义传入参数string 
DATA: lv_json_str TYPE string. 
 
6、将内表转成JSON 
lv_json_str = /ui2/cl_json=>serialize( data = ls_json assoc_arrays = abap_true ). 
 
7、创建请求 
  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. 
 
8、认证 
lo_http_client->propertytype_logon_popup = lo_http_client->co_disabled. 
 
  CALL METHOD lo_http_client->authenticate( 
    EXPORTING 
*     client   = '' 
*     proxy_authentication = 'X' 
      username = '用户名' 
      password = '密码' 
*                            LANGUAGE 
*     =        = 
*     'E'      = 
  ). 
 
*设置header 
    CALL METHOD lo_http_client->request->set_header_field 
      EXPORTING 
        name  = 'username' 
        value = lv_username. 
 
    CALL METHOD lo_http_client->request->set_header_field 
      EXPORTING 
        name  = 'password' 
        value = lv_password. 
 
  "设定传输请求内容格式以及编码格式 
  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. 
    "操作失败,获取失败原因 
    lo_http_client->get_last_error( IMPORTING message = message ). 
    code = 0. 
    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 = message ). 
    code = 0. 
    EXIT. 
  ELSE. 
    "读取返回返回内容 
    CLEAR lv_respon. 
    code = 1. 
    lv_respon = lo_http_client->response->get_cdata( ). 
 
    /ui2/cl_json=>deserialize( EXPORTING json = lv_respon assoc_arrays = abap_true           
 CHANGING data = ls_exp ). "ls_exp是返回参数结构 
  ENDIF. 
 
  CALL METHOD cl_demo_output=>display_json 
    EXPORTING 
      json = lv_response. 
 
 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/17980.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论