现在的位置: 首页 > 综合 > 正文

使用 HttpWebRequest 类调用 WEB 服务的示例(C#) 转

2012年10月21日 ⁄ 综合 ⁄ 共 2472字 ⁄ 字号 评论关闭

为了测试其中的 PROVISION 接口,利用了 System.Net.HttpWebRequest 类将《MISC系统短信SP接入指南-接口改造分册》文档中的示例 xml 发送到了 WEB 服务,并从 WEB 服务返回了对应的 Resp 包(也是一段 xml),下面就将代码贴出来:

     1、SyncOrderRelationReq 包的 xml 内容:

 


<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:xsd="http://www.w3.org/2001/XMLSchema"    xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"    xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
  
<SOAP-ENV:Header>
    
<TransactionID xmlns="http://www.monternet.com/dsmp/schemas/">00110318384464</TransactionID>
  
</SOAP-ENV:Header>
  
<SOAP-ENV:Body>
    
<SyncOrderRelationReq xmlns="http://www.monternet.com/dsmp/schemas/">
      
<Version>1.5.0</Version>
      
<MsgType>SyncOrderRelationReq</MsgType>
      
<Send_Address>
        
<DeviceType>0</DeviceType>
        
<DeviceID>0011</DeviceID>
      
</Send_Address>
      
<Dest_Address>
        
<DeviceType>400</DeviceType>
        
<DeviceID>0</DeviceID>
      
</Dest_Address>
      
<FeeUser_ID>
        
<UserIDType>1</UserIDType>
        
<MSISDN>13456781234</MSISDN>
        
<PseudoCode></PseudoCode>
      
</FeeUser_ID>
      
<DestUser_ID>
        
<UserIDType>1</UserIDType>
        
<MSISDN>13456781234</MSISDN>
        
<PseudoCode></PseudoCode>
      
</DestUser_ID>
      
<LinkID>SP</LinkID>
      
<ActionID>1</ActionID>
      
<ActionReasonID>1</ActionReasonID>
      
<SPID>419000</SPID>
      
<SPServiceID>-YYXXYYXX</SPServiceID>
      
<AccessMode>3</AccessMode>
      
<FeatureStr>MTA2NjIxNDQgREE=</FeatureStr>
    
</SyncOrderRelationReq>
  
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
 
    2、HttpWebRequest 调用 WEB 服务的代码:
 

System.Xml.XmlDocument doc = new XmlDocument();
doc.Load(
"c://SyncOrderRelationReq.xml");
MemoryStream ms 
= new MemoryStream();
doc.Save(ms);

System.Net.HttpWebRequest r = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://localhost/websrv/dsmp.asmx");

r.Method = "POST";
r.ContentType 
= @"text/xml;charset=utf-8";
r.Headers.Add(
"SOAPAction""/"" + "sim.SyncOrderRelation" + "/"");
r.Credentials 
= System.Net.CredentialCache.DefaultCredentials;

byte[] bytes = ms.ToArray();
r.ContentLength 
= bytes.Length;
Stream s 
= r.GetRequestStream();
s.Write(bytes, 
0, bytes.Length);
s.Close();

StreamReader sr = new StreamReader(r.GetResponse().GetResponseStream());
String retXml 
= sr.ReadToEnd();
sr.Close();
doc 
= new XmlDocument();
doc.LoadXml(retXml);
doc.Save(
"c://SyncOrderRelationResp.xml");

 
        这只是一个利用 HttpWebRequest 调用 WEB 服务的小例子,只需要将上面的那段 xml 保存为 c 盘下的 SyncOrderRelationReq.xml 文件中,调用后就会将 WEB 服务的返回结果保存在 c 盘的 SyncOrderRelationResp.xml 中了。

抱歉!评论已关闭.