Sqlserver调用api

虽然使用sqlserver去调用服务接口的情况比较少,但也可以去了解下对应的使用情况

一、首先要开启组件的配置

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'Ole Automation Procedures';
GO

 

二、调用webservice

1、接口信息获取

调用webservice的时候建议使用fiddler去获取一下发送数据过程用contenttype的类型以及调用接口的数据

2、使用sqlserver调用对应的接口以及结果

declare @ServiceUrl as varchar(1000) 
set @ServiceUrl = 'http://localhost:19930/LoginWebService.asmx/Login'
DECLARE @data varchar(max);
set @data='username=8&password=7'                  

Declare @Object as Int
Declare @ResponseText AS  varchar(1000)   ;      
Exec sp_OACreate 'Msxml2.ServerXMLHTTP.3.0', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'POST',@ServiceUrl,'false'
Exec sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Type','application/x-www-form-urlencoded'
Exec sp_OAMethod @Object, 'send', NULL, @data --发送数据
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
EXEC sp_OAGetErrorInfo @Object --异常输出
Select  @ResponseText 
Exec sp_OADestroy @Object
GO

三、调用webapi

 两者调用的方式基本如出一辙

1、接口信息获取

同样使用fiddler获取接口调用信息(因为该接口是GET就不需要看所传的参数)

2、接口调用以及结果

GET操作

declare @ServiceUrl as varchar(1000) 
set @ServiceUrl = 'http://xxxxx.com/beijing/139/1000000/TaxInfo?token=6d83d2adcff64594bd68614b6ae9e1c8'
DECLARE @data varchar(max);
set @data=''                  

Declare @Object as Int
Declare @ResponseText AS  varchar(8000)   ;      
Exec sp_OACreate 'Msxml2.ServerXMLHTTP.3.0', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'GET',@ServiceUrl,'false'
Exec sp_OAMethod @Object, 'send', NULL, @data --发送数据
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
EXEC sp_OAGetErrorInfo @Object --异常输出
Select  @ResponseText 
Exec sp_OADestroy @Object
GO

 

POST操作

declare @ServiceUrl as varchar(1000) 
set @ServiceUrl = 'http://xxxx.com/Feedback/Estimate'
DECLARE @data varchar(max);
--发送数据
set @data='CityName=SubmitSystemName=%E7%99%BE%E5%BA%A6%E5%8F%8D%E9%A6%88&OriginID=2d90660c-436c-4e12-bfa6-e849a06b2c51&Price=10000&IsAccurate=False&PriceType=1&UserKeyId=a669e4ec7bdc47a7b6c2c334ebe1a50c&signature=X8p3lIZT0Ba3LeiC6irm3%2FMnlE8%3D&time=1452735047291'                   

Declare @Object as Int
Declare @ResponseText AS  varchar(8000)   ;      
Exec sp_OACreate 'Msxml2.ServerXMLHTTP.3.0', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'POST',@ServiceUrl,'false'
Exec sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Type','application/x-www-form-urlencoded'
Exec sp_OAMethod @Object, 'send', NULL, @data --发送数据
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
EXEC sp_OAGetErrorInfo @Object --异常输出
Select  @ResponseText 
Exec sp_OADestroy @Object
GO

  

 

posted @ 2016-11-15 15:52  cloud_li  阅读(8884)  评论(3编辑  收藏  举报