WebService 之 Restful Tool

leintor發表於2012-08-28
透過WebService 傳送一個XML的Request,來獲取XML的Response
 
如何將 XSD 檔案轉化為類檔案呢?
XSD  /classes filename.xsd
 
private static bool RemoteCertValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
        {
            // TODO: validate server cert
            return true;
        }
 
private void button1_Click(object sender, EventArgs e)
        {
            ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertValidate);
                // setup request
                WebServiceRequest request = new WebServiceRequest();
                XmlSerializer s = new XmlSerializer(typeof(WebServiceRequest));
                MemoryStream ms = new MemoryStream();
                XmlTextWriter xmlWriter = new XmlTextWriter(ms, Encoding.UTF8);
                s.Serialize(xmlWriter, request);
                String requestXml = Encoding.UTF8.GetString(ms.ToArray());
                // send request
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(WebService_Http_URL);
                X509Certificate2 certPfx = new X509Certificate2();
                certPfx.Import("Certificate.pfx", "", X509KeyStorageFlags.PersistKeySet);
                req.ClientCertificates.Add(certPfx);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                byte[] requestXmlBytes = Encoding.UTF8.GetBytes(requestXml);
                req.ContentLength = requestXmlBytes.Length;
                Stream postStream = req.GetRequestStream();
                postStream.Write(requestXmlBytes, 0, requestXmlBytes.Length);
                postStream.Flush();
                postStream.Close();
                // get and unmarshal response
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream respStream = resp.GetResponseStream();
                StreamReader sr = new StreamReader(respStream, Encoding.UTF8);
                string responseXml = sr.ReadToEnd();
                s = new XmlSerializer(typeof(WebServiceResponse));
                WebServiceResponse respObj = (WebServiceResponse)s.Deserialize(new StringReader(responseXml));
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/20200170/viewspace-742088/,如需轉載,請註明出處,否則將追究法律責任。

相關文章