最近帮同事处理了一个中信银行银企直连接口的一个问题,同事反馈,使用STRANS转换XML后,encoding始终是'utf-16',就算指定了GBK也不行。尝试了很多办法始终不行,发到银行的数据中,中文始终是乱码。
Debug使用HTML视图看报文时也可以看到中文是乱码。
解决方案:
使用cl_sxml_string_writer=>create创建一个GBK编码的对象 ,用来做为STRANS的结果,最重要的是直接发转了编码后的XSTRING过去,不要 转STRING。因为我们的程序是UNICODE的,只要转成STRING,中文就会变成乱码。
返回的结果也一样,看下XSTRING,可以正常显示,如果直接转成STRING就也会变乱码。
主要代码:
ABAP
DATA: lv_url TYPE string.
DATA: lo_xml TYPE REF TO cl_sxml_string_writer.
DATA: x_xml TYPE xstring.
DATA: jsonstr TYPE string.
DATA: xmlstr TYPE string.
lo_xml = cl_sxml_string_writer=>create( encoding = 'GBK'
no_empty_elements = 'X' ).
TRY .
CALL TRANSFORMATION zqbtest_sample31
SOURCE header = header[]
item = item[]
RESULT XML lo_xml.
CATCH cx_st_error INTO lo_oref .
lv_msg = lo_oref->get_text( ) .
WRITE: / 'Error message:',lv_msg.
ENDTRY.
x_xml = lo_xml->get_output( ).
lv_url = 'http://192.168..:'.
cl_http_client=>create_by_url(
EXPORTING
url = lv_url
IMPORTING
client = DATA(lo_http_client)
EXCEPTIONS
argument_not_found = 1
plugin_not_active = 2
internal_error = 3
OTHERS = 4 ).
lo_http_client->propertytype_logon_popup = lo_http_client->co_disabled.
CALL METHOD lo_http_client->request->set_content_type
EXPORTING
content_type = 'text/xml; charset=GBK'.
CALL METHOD lo_http_client->request->set_method( 'POST' ).
CALL METHOD lo_http_client->request->set_data
EXPORTING
data = x_xml.
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 = DATA(lv_msg1) ).
EXIT.
ENDIF.
lo_http_client->receive(
EXCEPTIONS
http_communication_failure = 1
http_invalid_state = 2
http_processing_failed = 3 ).
IF sy-subrc <> 0 .
"操作失败,获取失败原因
lo_http_client->get_last_error( IMPORTING message = lv_msg ).
EXIT.
ENDIF.
DATA(response) = lo_http_client->response->get_data( ).
* ev_response = response.
CALL METHOD lo_http_client->close.