LoginSignup
2
2

More than 3 years have passed since last update.

【ABAP】JSON形式のデータを外部に送信(POST)する

Posted at

やること

SAP標準のフライト情報を、JSON形式で外部に送信する。
宛先の設定はT-CD:SM59で行う。

参考:How to Prepare JSON in ABAP & Send Response to Cloud?

手順

SM59で宛先設定

検証のみのため、httpbinを使用します。
※httpbinの使用方法などについては、Postmanなどで事前に検証してください

参考:APIクライアント開発時のモックに使えるhttpbinの紹介

接続テスト

RFC宛先:Z_HTTPBIN(任意)
接続タイプ:G
対象ホスト:httpbin.org
パス接頭辞:ブランク(接続確認のため)

image.png

image.png

接続テスト結果
image.png

接続テスト後

パス接頭辞に /post を追加する(httpbinでのPOST用のパス)
image.png

コーディング

クラス IF_HTTP_CLIENT を使用

Y_POST_JSON
  CONSTANTS lc_content    TYPE string VALUE 'Content-Type'.
  CONSTANTS lc_contentval TYPE string VALUE 'application/json'.

  DATA lo_http_client TYPE REF TO if_http_client.
  DATA lv_httpcode    TYPE i.
  DATA lv_reason      TYPE string.

* データ抽出
  SELECT *
    FROM sflight
    INTO TABLE @DATA(lt_flightdata).

* 内部テーブルからJSONに変換
  DATA(lv_json) = /ui2/cl_json=>serialize( lt_flightdata ).

* 変換結果の確認
  cl_demo_output=>display_json( lv_json ).

* 宛先の設定
  CALL METHOD cl_http_client=>create_by_destination
    EXPORTING
      destination              = 'Z_HTTPBIN'  "SM59で作成した宛先
    IMPORTING
      client                   = lo_http_client
    EXCEPTIONS
      argument_not_found       = 1
      destination_not_found    = 2
      destination_no_authority = 3
      plugin_not_active        = 4
      internal_error           = 5
      OTHERS                   = 6.
  IF sy-subrc <> 0.
* 省略
  ENDIF.

  lo_http_client->refresh_request( ).
  lo_http_client->request->set_version( if_http_request=>co_protocol_version_1_0 ).

* メソッドの設定(POST)
  CALL METHOD lo_http_client->request->set_method
    EXPORTING
      method = lo_http_client->request->co_request_method_post.

* ヘッダ部の設定
  CALL METHOD lo_http_client->request->set_header_field
    EXPORTING
      name  = lc_content
      value = lc_contentval.

* JSONデータの設定
  CALL METHOD lo_http_client->request->set_cdata
    EXPORTING
      data = lv_json.

* データ送信
  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 ).

* ステータス取得
  CALL METHOD lo_http_client->response->get_status
    IMPORTING
      code   = lv_httpcode
      reason = lv_reason.

* 結果出力
  WRITE lv_httpcode.
  WRITE lv_reason.

実行

変換結果の確認

cl_demo_outputでJSON変換結果を確認
参考:【ABAP】内部テーブルをJSONに変換する
image.png

実行結果

image.png

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2