delphi中URL的汉字编码

2018-10-31

show.asp?sort=全部&sortlevel=1&gorq=供&n=5&sitename=全部&img=yes&imgfile=/images/dot_g.gif
诸如这样的形式,在百度查询会转成GB2312的编码,每个汉字对应2个%xx%xx ,但是在google,每个汉字则对应的三个%xx%xx%xx,采用的是unicode编码
在delphi2010中,因为引入unicode的缘故,默认的成了3个%xx,导致我的程序出现问题,找了半天,每一个函数能够实现全URL的自动检测编码,所以自己写了一个,共享给大家:
uses
httpapp;
function urlencode(Aurl: string): string;
var
 i: integer;
 stmp,Tstmp: string;
begin
 result:=Aurl;
 if length(Aurl) > 0 then
 begin
 for i := 1 to length(Aurl) do
 begin
 if Integer(Ord(Aurl[i])) >255 then
 begin
 stmp := copy(Aurl, i, 1);
 Tstmp:=HttpEncode(stmp);
 result:=stringreplace(result,stmp,Tstmp,[]);
 end;
 end;
 end;
end;

使用:
URL :=urlencode(URL);
则URL中的汉字自动转为gb2312的%xx的编码。
阅读27