oracle PL/SQL:带有 UTF8 字符串的 UTL_HTTP POST 导致字符损坏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21851717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 05:30:46  来源:igfitidea点击:

PL/SQL: UTL_HTTP POST with UTF8 string results in broken characters

oraclehttppostutf-8plsql

提问by Federico Elles

I want to send an UTF8 json string via utl_http to a node.js Server via POST. Sending the string

我想通过 utl_http 将一个 UTF8 json 字符串通过 POST 发送到 node.js 服务器。发送字符串

["Sant Julià de Lòria"]

does arrive as

确实到达

["Sant Juli??? de L???ria"]

The PL/SQL code goes like:

PL/SQL 代码如下:

FUNCTION http_post_varchar(
    p_url          VARCHAR2,
    p_request_body VARCHAR2 )
  RETURN VARCHAR2
AS
  req   UTL_HTTP.REQ;
  resp  UTL_HTTP.RESP;
  value VARCHAR2(32767);  -- URL to post to
  v_url VARCHAR2(200) := p_url;
  -- Post Parameters
  v_param VARCHAR2(32767) := p_request_body;
  v_param_length NUMBER := length(v_param);
BEGIN
  req := UTL_HTTP.BEGIN_REQUEST (url=> v_url, method => 'POST');
  UTL_HTTP.SET_HEADER (r      =>  req,
                       name   =>  'Content-Type',
                       value  =>  'application/json;charset=UTF-8');
  UTL_HTTP.SET_HEADER (r      =>   req,
                       name   =>   'Content-Length',
                       value  =>   v_param_length);
  UTL_HTTP.WRITE_TEXT (r      =>   req,
                       data   =>   v_param);

  resp := UTL_HTTP.GET_RESPONSE(req);
  LOOP
    UTL_HTTP.READ_LINE(resp, value, TRUE);    
  END LOOP;
  UTL_HTTP.END_RESPONSE(resp);
  RETURN 'OK';
EXCEPTION
  WHEN UTL_HTTP.END_OF_BODY THEN
    UTL_HTTP.END_RESPONSE(resp);
  RETURN 'OK';
END http_post_varchar;

回答by Luscus

You should change your code to:

您应该将代码更改为:

UTL_HTTP.SET_BODY_CHARSET('UTF-8');
UTL_HTTP.SET_HEADER (r      =>   req,
                     name   =>   'Content-Length',
                     value  =>    LENGTHB(v_param));

UTL_HTTP.WRITE_RAW (r    => req,
                    data => UTL_RAW.CAST_TO_RAW(v_param));

LENGTHB for byte length because of UTF-8. Otherwise the calculated length will be false and you get an error on the target side (unexpected end of inputor something).

由于 UTF-8,字节长度为 LENGTHB。否则计算出的长度将是错误的,并且您会在目标端出现错误(输入的意外结束或其他内容)。