SAP ABAP 发送/调用HTTP POST/GET请求的通用方法

该文章展示了如何在ABAP中使用if_http_client类来调用HTTP服务,包括POST请求的实现。首先,通过Postman测试服务接口,然后在ABAP中序列化数据并设置请求头和内容类型,最后发送HTTP请求并处理响应。示例代码涵盖了错误处理和字符编码转换。

使用类if_http_client基本可以解决大多数ABAP调用http服务的问题。在调用服务前可以先用postman来测试服务,确定可输入的参数。

通用代码如下:

report  z_http_post.

" data to post
data: gt_accbal like standard table of zglaccbalance with header line.
data: lv_json_str type string. "发送报文
data: gr_serializer type ref to zcl_trex_json_serializer.

start-of-selection.
  " get data
  call function 'Z_BAPI_GLACCPERIODBALANCES'
    exporting
      companycode  = 'Z900'
      fiscalyear   = '2020'
      fiscalperiod = '10'
    tables
      acc_balances = gt_accbal.

  " 序列化
  create object gr_serializer
    exporting
      data   = gt_accbal[] .
  call method gr_serializer->serialize( ) .
  lv_json_str = gr_serializer->get_data( ).

  " 发送http post请求
  perform http_post.


*&---------------------------------------------------------------------*
*&      Form  HTTP_POST
*&---------------------------------------------------------------------*
form http_post .
  data: lv_url type string.     "http 服务接口地址
  data: lo_http_client  type ref to if_http_client.
  data: lv_len type i."发送报文长度
  data: lv_resp type string.

  data: lv_message  type string.
  data: lv_mtype    type bapi_mtype.
  data: lv_code     type sysubrc.

  " 设置http接口地址
  lv_url = 'http://192.168.3.14:5000/testpost/'.

  "创建客户端请求
  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.

  " 设置content type和character set
  lo_http_client->request->set_content_type( content_type = 'application/json; charset=utf-8' ).

  " 设置方法为 post
  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 code = lv_code ).
    lv_mtype = '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_message code = lv_code  ).
    lv_mtype = 'E'.
    write: lv_message, lv_code.
    exit.
  else.
    " 读取返回返回内容
    clear lv_resp.
    lv_resp = lo_http_client->response->get_cdata( ).
  endif.
  write:lv_resp.
*  MESSAGE LV_MESSAGE TYPE LV_MTYPE .
endform.                    "HTTP_POST

再举一个例子

以post方式为例,request的参数都是通过body来传输的。正常服务发起比较简单,通过if_http_client->request->set_data设置传输值,if_http_client->request->set_header_field设置header的content-type。如果服务端对body的数据字符集有要求,比如gbk,则需要先将body数据进行jbk转码,然后在if_http_client->request->set_content_type中设置content-type,示例代码如下:

  "设定传输请求内容格式以及编码格式
  lo_http_client->request->set_content_type( content_type = 'application/XML; charset=GBK' ).

  "设定调用服务
  lo_http_client->request->set_method( if_http_request=>co_request_method_post ).

  CLEAR:lv_result_xstring.
  lv_result_xstring = cl_abap_codepage=>convert_to(
        source      =  uv_reqxml
        codepage    = 'GBK'
                          ).
  lv_len = xstrlen( lv_result_xstring ).
  lo_http_client->request->set_data(
     EXPORTING
       data   = lv_result_xstring
       offset = 0
       length = lv_len ).


  lo_http_client->send(
    EXCEPTIONS
      http_communication_failure = 1
      http_invalid_state         = 2 ).

  lo_http_client->receive(
    EXCEPTIONS
      http_communication_failure = 1
      http_invalid_state         = 2
      http_processing_failed     = 3 ).


*  lv_result_string = lo_http_client->response->get_cdata( ).

  CLEAR:lv_result_xstring,lv_result_string.
  lv_result_xstring = lo_http_client->response->get_data( ).
  lv_result_string  = cl_abap_codepage=>convert_from(
        source      =  lv_result_xstring
        codepage    = 'GBK' ).

<think>我们正在讨论SAP中如何设置HTTPPOST请求请求头。根据用户提供的引用,特别是引用[1]提到了HTTPPOST方法,但并没有直接给出设置请求头的示例。我们需要结合SAP环境(如ABAP)来回答。在SAPABAP中,我们通常使用CL_HTTP_CLIENT类来创建HTTP客户端并设置请求。以下是一个典型的步骤:1.创建HTTP客户端实例。2.设置目标URL。3.设置请求方法(如POST)。4.设置请求头(Header)。5.设置请求体(Body,如果需要)。6.发送请求并获取响应。重点在于设置请求头。我们可以使用`set_header_field`方法来设置单个请求头字段,或者使用`set_header_fields`方法来设置多个。示例代码如下:```abapDATA:lo_http_clientTYPEREFTOif_http_client,lv_urlTYPEstringVALUE'https://example.com/api'."创建HTTP客户端CALLMETHODcl_http_client=>create_by_urlEXPORTINGurl=lv_urlIMPORTINGclient=lo_http_client."设置请求方法POSTlo_http_client->request->set_method('POST')."设置请求头"单个设置lo_http_client->request->set_header_field(name='Content-Type'value='application/json').lo_http_client->request->set_header_field(name='Authorization'value='Beareryour_token')."或者一次性设置多个DATA:lt_header_fieldsTYPEtihttpnvp.APPEND:name='Content-Type'value='application/json'TOlt_header_fields,name='Authorization'value='Beareryour_token'TOlt_header_fields.lo_http_client->request->set_header_fields(fields=lt_header_fields)."设置请求体(如果有)DATA(lv_json)='{"key":"value"}'.lo_http_client->request->set_cdata(lv_json)."发送请求lo_http_client->send()."接收响应lo_http_client->receive()."处理响应DATA(lv_response)=lo_http_client->response->get_cdata().```注意:上述代码中,我们首先创建了一个HTTP客户端,然后设置请求方法POST。接着,我们使用`set_header_field`分别设置Content-Type和Authorization请求头。也可以使用`set_header_fields`一次设置多个。引用[1]中提到了POST方法最初由HTML表单设计用于向服务器发送数据,在SAP中我们同样可以设置请求头来传递必要的信息。对于SAP系统,特别是ABAP程序,上面的示例展示了如何设置HTTPPOST请求头。这在实际应用中非常常见,例如调用OData服务(如引用[2]提到的SAPOData服务)或调用外部API。另外,引用[4]提到了SAPABAP批量翻译工具,虽然与当前问题不直接相关,但展示了SAPHTTP请求的应用场景(如调用翻译API)。因此,用户的问题可以通过上述ABAP代码示例得到解决。§§相关问题§§1.在SAPABAP中如何处理HTTP响应?2.如何设置SAPHTTP请求的超时时间?3.在SAP调用HTTPS服务需要什么额外配置?</think> ### SAP HTTP POST 请求头设置示例 在SAP ABAP中设置HTTP POST请求头主要使用`set_header_field`方法。以下是具体实现步骤和示例代码: #### 核心代码示例 ```abap DATA: lo_http_client TYPE REF TO if_http_client, lv_url TYPE string VALUE 'https://your.api.endpoint'. " 创建HTTP客户端 CALL METHOD cl_http_client=>create_by_url EXPORTING url = lv_url IMPORTING client = lo_http_client. " 设置请求方法POST lo_http_client->request->set_method( 'POST' ). " 设置请求头(关键步骤) lo_http_client->request->set_header_field( name = 'Content-Type' " 内容类型 value = 'application/json' ). lo_http_client->request->set_header_field( name = 'Authorization' " 授权令牌 value = 'Bearer your_access_token' ). lo_http_client->request->set_header_field( name = 'X-Custom-Header' " 自定义头部 value = 'CustomValue' ). " 设置请求体 DATA(lv_json_body) = '{"key": "value"}'. lo_http_client->request->set_cdata( lv_json_body ). " 发送请求 lo_http_client->send( ). lo_http_client->receive( ). " 处理响应 DATA(lv_response) = lo_http_client->response->get_cdata( ). ``` #### 关键说明 1. **常用请求头**: - `Content-Type`:指定请求体格式,常用值: - `application/json` - `application/xml` - `text/plain` - `Authorization`:认证令牌(如OAuth 2.0的`Bearer token`) - `Accept`:声明可接受的响应格式 - `X-Requested-With`:标识AJAX请求(值为`XMLHttpRequest`) 2. **SAP特殊处理**: - 连接外部系统时需配置**HTTP目标**(事务码:SM59) - 使用HTTPS需配置SSL证书 - SAP Cloud Platform需使用`cl_http_destination_provider` 3. **调试建议**: - 使用`lo_http_client->request->get_header_fields( )`验证头设置 - 事务码`SRT_UTIL`检查SSL配置 - 第三方工具(如Postman)模拟请求 > 引用说明:HTTP POST方法最初由HTML表单设计用于向服务器发送数据,在SAP中通过ABAP类实现相同协议规范[^1]。SAP系统通过HTTP客户端库封装了底层通信细节[^4]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值