delphi调用java编写的http接口

采用delphi7的indy组件


提交的数据中包含中文,需要进行URL编码:

function UrlEncode(const ASrc: string): string;
const
  UnsafeChars = '*#%<>+ []';  {do not localize}
var
  i: Integer;
begin
  Result := '';    {Do not Localize}
  for i := 1 to Length(ASrc) do begin
    if (AnsiPos(ASrc[i], UnsafeChars) > 0) or (ASrc[i]< #32) or (ASrc[i] > #127) then begin
      Result := Result + '%' + IntToHex(Ord(ASrc[i]), 2);  {do not localize}
    end else begin
      Result := Result + ASrc[i];
    end;
  end;
end;


procedure TForm1.BitBtn1Click(Sender: TObject);
var
  Param:String;
  F_Params:TStringList;
  RStream:TStringStream;
begin
 try
   F_Params:=TStringList.Create;
   RStream:=TStringStream.Create('');
   Param:='为要提交的数据,需要用URL编码';
   Param:=Trim(Param);
   F_Params.Add(Param); //添加的第一个参数
   F_Params.Add('CurToken=8eeafa5eb583766c'); //添加的第二个参数 

//参数顺序一定要与java接口中定义的参数顺序一致,否则调用失败


   IdHTTP1.HTTPOptions:=IdHTTP1.HTTPOptions-[hoForceEncodeParams];
   IdHTTP1.Request.UserAgent:='Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)';
   IdHTTP1.Request.AcceptCharSet:='GBK,utf-8;q=0.7,*;q=0.3';
   IdHTTP1.Request.AcceptLanguage:='zh-CN,zh;q=0.8';
   IdHTTP1.Post('URL接口地址',F_Params,RStream);
   showmessage(Utf8ToAnsi(RStream.DataString));  // 返回值中如果有中文会出现乱码,所以需要经过Utf8ToAnsi来解码
 finally
   FreeAndNil(F_Params);
   FreeAndNil(RStream);
 end;
end;


posted @ 2014-12-05 08:56  骑着骆驼逛沙漠  阅读(2062)  评论(0编辑  收藏  举报