1. 程式人生 > >delphi呼叫java編寫的http介面

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;