发送from-data请求

[[Oracle APEX]]

场景/背景

Oracle Apex文档
和第三方对接时, 其中获取token的方式是post form-data 形式. 如下图postman调用, 尝试Apex的请求发现走不通 OsXM1-2024-09-18-16-37-34
Apex的请求

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
BEGIN
    apex_json.initialize_clob_output;
    apex_json.open_object;
    apex_json.write('grant_type', 'password');
    apex_json.write('client_id', g_client_id);
    apex_json.write('EnterpriseKey', g_EnterpriseKey);
    apex_json.write('username', g_username);
    apex_json.write('password', g_password);
    apex_json.close_object;
    l_json_clob := apex_json.get_clob_output;
    apex_json.free_output;
    apex_web_service.g_request_headers.DELETE; -- 清理请求头
    apex_web_service.g_request_headers(1).NAME := 'Content-Type';
    apex_web_service.g_request_headers(1).VALUE := 'application/json';
    l_response_json_clob := apex_web_service.make_rest_request(
            p_url => g_get_token_url,
            p_http_method => 'POST',
            p_body => l_json_clob);
END;

解决方案

参考stackoverflow
参考博主

依据postman 导出python 脚本, 通过python 脚本查看最终发给对方的body是什么,见下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import requests

url = "https://xxxxxxx.xxxxxxx.com/token"

payload = {
    'grant_type': 'password',
    'client_id': '89AF',
    'EnterpriseKey': '4F2B',
    'username': 'xxxxxxx',
    'password': 'qqqqqqq'
}
files = [

]
headers = {
    # 'Content-Type': 'multipart/form-data'
    # 'Content-Type': 'application/json'
    'Content-Type': 'application/x-www-form-urlencoded'
}
req = requests.Request('POST', url, headers=headers, data=payload, files=files)
r = req.prepare()
print(r.body)
# grant_type=password&client_id=89AF&EnterpriseKey=4F2B&username=xxxxxxx&password=qqqqqqq
s = requests.Session()
response = s.send(r)
print(response.text)

发现居然是 key1=value1&key2=value2 好奇怪… 再改下下apex的code,搞定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
 BEGIN

    json_sample := 'grant_type=password&client_id=' || g_client_id || '&' || 'EnterpriseKey='
        || g_EnterpriseKey || '&' || 'username='
        || g_username || '&' || 'password=' || g_password;

    apex_web_service.g_request_headers.DELETE; -- 清理请求头
    apex_web_service.g_request_headers(1).NAME := 'Content-Type';
    apex_web_service.g_request_headers(1).VALUE := 'application/x-www-form-urlencoded';
    l_response_json_clob := apex_web_service.make_rest_request(
            p_url => g_get_token_url,
            p_http_method => 'POST',
            p_body => json_sample);
    apex_json.parse(l_response_json_clob);
    access_token := apex_json.get_varchar2(p_path=>'access_token');
    dbms_output.put_line(access_token);
END;

OsXM1-2024-09-18-16-58-15

Licensed under CC BY-NC-SA 4.0
最后更新于 2025-12-02 10:56
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计