使用 CL_HTTP_CLIENT 时编码混乱

Encoding messed up when using CL_HTTP_CLIENT

我在 ABAP 中发出这样的 http 请求:

    CALL METHOD cl_http_client=>create_by_url
      EXPORTING
        URL    = url
      IMPORTING
        client = client.

    client->request->set_header_field(
      name  = 'Content-Type'
      value = 'application/json; charset=utf-8'
    ).

    client->send(
      EXCEPTIONS
        http_communication_failure = 1
        http_invalid_state         = 2
        http_processing_failed     = 3
        http_invalid_timeout       = 4
        OTHERS                     = 5
    ).

    CHECK sy-subrc = 0.

    client->receive(
      EXCEPTIONS
        http_communication_failure = 1
        http_invalid_state         = 2
        http_processing_failed     = 3
        OTHERS                     = 4
    ).

    string_response = client->response->get_cdata( ).

string_response 编码不正确,数据应该是 "{"CompanyName": "Uberlândia"}",但我得到 "{"CompanyName": "Uberlândia"}",即使我通过 [=22] =] 根据要求 header 'Content-Type'

可能是响应在 UTF-8 中编码,但在 HTTP 响应中未提及。

所以你必须使用 get_data 而不是 get_cdata,进入类型 XSTRING(字节串)的变量,然后解码它的 UTF-8 值进入 STRING 类型的变量(字符串)。

DATA: xstring_response TYPE xstring,
      string_response  TYPE string.

" Get response as a string of bytes
xstring_response = client->response->get_data( ).

" Assume response is UTF-8 text, so decode it
" (UTF-8 is the default parameter value of method convert_from)
string_response = cl_abap_codepage=>convert_from( xstring_response ).