调用部署在SSL下的WebService的方法

调用部署在SSL下的WebService的方法
(Microsoft .NET Framework SDK v2.0)
 
  
private void btnCall_Click(object sender, EventArgs e)
  
{     
   
// SOAP 请求信息(从WSDL分析得出)
   StringBuilder sb = new StringBuilder();
   sb.Append(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n");
   sb.Append(
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">\r\n");
   sb.Append("  <soap:Body>\r\n");
   sb.Append(
"    <m:getData xmlns=\"http://127.0.0.1/xfireWebService/services/helloWorld\" />\r\n");
   
//sb.Append("    <getData xmlns=\"http://tempuri.org/\" />\r\n");
   sb.Append("  </soap:Body>\r\n");
   sb.Append(
"</soap:Envelope>\r\n");
   
byte[] sendByte = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
 
   
try
   
{
    
// 加载证书(这个证书从IE中导出来的)
    string certificateFile = @"c:\out.cer";
    X509Certificate certificate 
= X509Certificate.CreateFromCertFile(certificateFile);
 
    
// 验证
    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
 
    
// 生成Web请求
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://192.168.100.153/CUPIT/MessageIO");
    
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:2022/ws/Service.asmx");
    
    
// 设置请求属性
    request.ClientCertificates.Add(certificate);
    request.Method 
= "POST";
    request.ContentType 
= "text/xml; charset=utf-8";
    request.ContentLength 
= sendByte.Length;
 
    Stream rStream 
= request.GetRequestStream();
    
//发送SOAP文件
    rStream.Write(sendByte, 0, sendByte.Length);
 
    
// 获得服务器相应(返回值)
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    Stream receiveStream 
= response.GetResponseStream();
    StreamReader readStream 
= new StreamReader(receiveStream, Encoding.UTF8);
 
    
// 把反回值保存到文件里
    string getDataFile = @"c:\getData.xml";
    
if (File.Exists(getDataFile))
    
{
     File.Delete(getDataFile);
    }

    FileStream fs 
= new FileStream(getDataFile, FileMode.Create);
    StreamWriter sw 
= new StreamWriter(fs, Encoding.UTF8);
 
    sw.Write(readStream.ReadToEnd());
    sw.Close();
    fs.Close();
 

    MessageBox.Show(
"OK");
    request.GetResponse();
    response.Close();
    readStream.Close();
   }

   
catch (Exception ex)
   
{
 
    MessageBox.Show(ex.ToString());
   }

  }

public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  
{
   
return true;
  }
posted @ 2007-05-18 14:56  轻松  阅读(1191)  评论(0编辑  收藏  举报