![]() |
| ||
|
|
Новости |
Поиск |
FAQ |
Статьи |
Книги |
Новости VCL
| | Форумы ЧАТ |
Орешник |
|
| |||
| |||
« предыдущая ветвь | форум | следующая ветвь »
GET-запрос в формате UTF-8 [D6, WinXP]
leonidus © (2008-08-06 19:52:00)Делаю GET-запрос через INDY к сервису Google Translation, строка запроса:
" http://translate.google.com/translate_t?text='+rq+'&langpair=de|ru"
где rq - переменная, содержащая немецкое слово, сама rq это widestring, ее я беру из TNT-компонента поддерживающего юникод. Но данные на сервер нужно отправлять в UTF-8, в связи с чем вопрос, как widestring сконвертировать в формат UTF-8 пригодный для вставки в URL-запрос?
(2009-02-20 22:36:00) [1]Удалено модератором
Eraser (2009-01-19 08:34:00) [2]> [3] leonidus (07.08.08 13:26)
оффтоп: подозрительные какие-то алгоритмы... может лучше регулярные выражения?
по сабжу: возможно это поможет https://forums.codegear.com/thread.jspa?threadID=8925&tstart=0 .
busrider (2009-01-19 00:54:00) [3]eFront-Р?нтернет магазин Бытовой Рё компьютерной техники www.e-front.com.ua
Slym (2008-08-08 11:34:00) [4]leonidus (07.08.08 13:26) [3]
И вообще чем [2] не нравится?
Slym (2008-08-08 11:32:00) [5]
function WideStr2UTF8URLEncode(const WStr:WideString):string;
var
UStr:UTF8String;
i:integer;
begin
UStr:=UTF8Encode(WStr);
result:='';
if length(UStr)>0 then
for i:=1 to length(UStr) do
result:=result+'%'+IntToHex(ord(UStr[i]),2);
end;
han_malign (2008-08-08 09:15:00) [6]
> function CharToHex( c: widechar ): string;
RFC-1738:
In most URL schemes, the sequences of characters in different parts
of a URL are used to represent sequences of octets used in Internet
protocols. For example, in the ftp scheme, the host name, directory
name and file names are such sequences of octets, represented by
parts of the URL. Within those parts, an octet may be represented by
the chararacter which has that octet as its code within the US-ASCII
coded character set.
In addition, octets may be encoded by a character tripletconsisting
of the character "%" followed by the twohexadecimal digits(from
"0123456789ABCDEF") which forming the hexadecimal value of the octet.
(The characters "abcdef" may also be used in hexadecimal encodings.)
Alucard (2008-08-08 01:23:00) [7]Google translate принимает параметр ie, определяющий енкодинг, например, ie=UTF8. Не могу сказать, поможет ли в данном случае, но на странице сервиса он используется.
leonidus (2008-08-07 14:54:00) [8]Удалено модератором
leonidus (2008-08-07 14:54:00) [9]Удалено модератором
leonidus (2008-08-07 13:26:00) [10]Viktorious спасибо за наводку, но при ближайшем рассмотрении оказалось что UTF8 не всегда корректно принимается скриптом, по всей вероятности запрос должен состоять из HEX-кодов каждой буквы с добавлением перед каждым кодом знак %.
Делаю так:
function CharToHex( c: widechar ): string;
begin
Result := '%' + IntToHex( Ord( c ), 2 );
end;
text:=trim(TntMemo1.Text); //в text
Text_hex:='';
for i:=1 to length(text) do
Text_hex:=Text_hex+CharToHex(text[i]);
try
st:='';
st:=IdHTTP1.Get(' http://translate.google.com/translate_t?text='+Text_hex+'&langpair=de|ru');
except
end;
//парсим
p1:=ansipos('',st);
p2:=ansipos('',st);
res:=copy(st,p1+1,p2-p1-1);
TntMemo2.Text:=res;
так вот если переводить с английского на русский например "hello" то на выходе получаю "ъДТБЧУФЧХКФЕ" что означает "Здравствуйте". А если с немецкого на русский слово "Wörterbuch", то получаю "Словарь" что вроде похоже на "словарь", но вопрос, почему для разных входных языков кодировка русского разная и как в обоих случаях ее привести к читаемому виду?
Slym (2008-08-07 12:28:00) [11]
procedure TForm1.Button2Click(Sender: TObject);
var
Data:TStringList;
res:string;
begin
Data:=TStringList.Create;
try
Data.Values['text']:=UTF8Encode(WideString('ру'));
res:=IdHTTP1.Post(' http://translate.google.com/translate_t',Data);
finally
Data.Free;
end;
end;
Viktorious (2008-08-07 00:20:00) [12]System.pas:
{ WideString <-> UTF8 conversion }
function UTF8Encode(const WS: WideString): UTF8String;
function UTF8Decode(const S: UTF8String): WideString;
Хинт: одна из самых полезных кнопок в Делфи - это F1 ;)