一、了解下x-www-form-urlencoded形式对于SAP来说有啥区别
简单来说,
1.raw格式就是标准的json格式:{“Name”:“John Smith”,“Age”: 23}
2.x-www格式是要转化一下的:Name=John+Smith&Age=23
字段与字段相互连接要用 & 符号,空格用 + 连接。所以说当你的关键参数里面带有这些特殊符号时,就要用方法转化一下。
二、具体实例。
先使用Postman跑一下,ok没有问题,可以通畅。关键信息按照你的接口来,我的接口信息上马了。
然后写ABAP代码:
DATA: len TYPE i, "发送报文长度
len_string TYPE string,
url TYPE string, "接口地址
http_client TYPE REF TO if_http_client, "http客户端
post_string TYPE string,
result TYPE string.
DATA: it_header TYPE tihttpnvp,
gv_json_in TYPE string VALUE '' .
START-OF-SELECTION.
" url = 'https://api.map.baidu.com/weather/v1/?district_id=222405&data_type=all&ak=cvqVbWx3ruVm63LqMbuW43K3oqNOodBT'.
url = 'http://这是个具体的网址,你需要粘贴上你的网址token'.
cl_http_client=>create_by_url(
EXPORTING url = url "服务提供方服务地址
IMPORTING client = DATA(lo_client)
).
"调取方式:get 或者为 post
lo_client->request->set_method( if_http_request=>co_request_method_post ).
" lo_client->request->set_method( if_http_request=>co_request_method_get ).
"设置抬头字段
CALL METHOD lo_client->request->set_header_field
EXPORTING
name = 'Content-Type'
value = 'application/x-www-form-urlencoded'. "为这种形式的,需要设置抬头格式
"返回格式。为json的
lo_client->response->if_http_entity~set_content_type( content_type = 'application/json' ).
*lo_client->response->get_header_field( name = 'x-csrf-token' ).
*lo_client->response->get_cookies( CHANGING cookies = lt_cookies ).
DATA:lv_username TYPE string.
DATA:lv_password TYPE string.
"为这种x-www-form-urlencoded形式的,需要把变量全部转译一下,比如&符号的
lv_username = cl_http_utility=>escape_url( 'cha填写关键信息' ).
lv_password = cl_http_utility=>escape_url( 'O0&J人工打码' ).
gv_json_in = 'grant_type=password' && "固定值
'&username=' && lv_username &&
'&password=' && lv_password &&
'&client_id=crm' . "固定值
DATA(lv_len) = strlen( gv_json_in ).
** 设置post接口body参数
lo_client->request->set_cdata( data = gv_json_in length = lv_len ).
** 发送数据
lo_client->send(
" EXPORTING
" timeout = co_timeout_default " Timeout of Answer Waiting Time
EXCEPTIONS
http_communication_failure = 1 " Communication Error
http_invalid_state = 2 " Invalid state
http_processing_failed = 3 " Error When Processing Method
http_invalid_timeout = 4 " Invalid Time Entry
OTHERS = 5
).
IF sy-subrc <> 0.
result = '接口接受响应失败'.
ENDIF.
**********************************************************************
** 接收返回参数
lo_client->receive(
EXCEPTIONS
http_communication_failure = 1 " Communication Error
http_invalid_state = 2 " Invalid state
http_processing_failed = 3 " Error When Processing Method
OTHERS = 4
).
IF sy-subrc <> 0.
result = '接口接受响应失败'.
ENDIF.
result = lo_client->response->get_cdata( ).
lo_client->close( ).
" WRITE: url.
WRITE: / result.
DEBUG看下过程,发现&符号是已经转义了
然后调取成功。
参考资料:
1.https://blog.csdn.net/BinGeneral/article/details/123607105 -斌将军SAP HTTP调用其他系统接口
感谢
同事小何
学习群-派蒙
学习群-fufu可爱捏
分享使我快乐,我是寒武青锋~!