教程-Delphi调用C# WEBSERVICE,二

第二步:将webserivce的WSDL导入到该dll工程中,如何导,方法至少有两种,我说简单的一种:

file->new->other->WebService->WSDL Importer,(将C#的WSDL输入)然后delphi会自动给你生成了一个pas文件,

(比如我们当前例子的服务地址是:http://localhost/AttributeTesting/AttributeTesting.asmx

如果你想输入WSDL那么就是http://localhost/AttributeTesting/AttributeTesting.asmx?wsdl

function GetServiceSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): ServiceSoap;

const

defWSDL = ’http://localhost/webserver/Service.asmx?WSDL’;

defURL = ’http://localhost/webserver/Service.asmx’;

defSvc = ’Service’;

defPrt = ’ServiceSoap’;

var

RIO: THTTPRIO;

begin

Result := nil;

if (Addr = ’’) then

begin

if UseWSDL then

Addr := defWSDL

else

Addr := defURL;

end;

if HTTPRIO = nil then

RIO := THTTPRIO.Create(nil)

else

RIO := HTTPRIO;

try

//RIO.HTTPWebNode.UseUTF8InHeader:=True; //

在此添加一句,修改编码方案。

Result := (RIO as ServiceSoap);

if UseWSDL then

begin

RIO.WSDLLocation := Addr;

RIO.Service := defSvc;

RIO.Port := defPrt;

end else

RIO.URL := Addr;

RIO.HTTPWebNode.UseUTF8InHeader:=True;//如果出现乱码对于中文参数必须加上

finally

if (Result = nil) and (HTTPRIO = nil) then

RIO.Free;

end;

end;

initialization

InvRegistry.RegisterInterface(TypeInfo(ServiceSoap), ’http://localhost/webserver/’, ’utf-8’);

InvRegistry.RegisterDefaultSOAPAction(TypeInfo(ServiceSoap), ’http://localhost/webserver/%operationName%’);

//对于无法识别传入的参数的问题,需要手工加上下面这一句>......

InvRegistry.RegisterInvokeOptions(TypeInfo(ServiceSoap), ioDocument);

3.使用delphi调用上面的dll

就一个函数,没有什么好说的:

procedure TForm1.Button1Click(Sender: TObject);

type

GetNumTotal=function(a,b:integer):integer;stdcall;

var

Th:Thandle;

Tf:GetNumTotal;

Tp:TFarProc;

begin

Th:=LoadLibrary(’mywebservice.dll’); {装载DLL}

if Th>0 then

try

Tp:=GetProcAddress(Th,PChar(’GetNum’));

if Tp<>nil

then begin

Tf:=GetNumTotal(Tp);

Edit1.Text:=IntToStr(Tf(1,3)); {调用GetNumTotal函数}

end

else

ShowMessage(’GetNumTotal函数没有找到’);

finally

FreeLibrary(Th); {释放DLL}

end

else

ShowMessage(’mywebservice.dll没有找到’);

end;

public static extern int GetNum(int a, int b);

private void button1_Click(object sender, EventArgs e)

{

int a,b,i;

a=10;

b =20;

i=GetNum(a,b); //第一次比较慢(webserivce的唯一弊端!!!!)

textBox1.Text = i.ToString();

}