将HTTP请求代码转换为HTTPS请求代码

时间:2009-12-29 06:28:32

标签: asp.net xml http web-services https

我有以下代码在HTTP协议上发送xml文件并从webserver获取响应作为xml文件,并且其工作正常与HTTP协议,但现在我需要将这样的XML文件发送到HTTPS协议(不是http)并需要从中获取响应作为xml文件。发送xml文件并从HTTP获取响应的代码是:

    string targetUri = "http://www.hostelspoint.com/xml/xml.php"; /*this will be like: "https://www.hostelspoint.com/xml/xml.php"*/
    System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
    reqDoc.Load(Server.MapPath("~\\getdetail.xml"));
    string formParameterName = "OTA_request";
    string xmlData = reqDoc.InnerXml;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
    string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
    //string sendString =  HttpUtility.UrlEncode(xmlData);

    byte[] byteStream;
    byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = byteStream.LongLength;

    using (Stream writer = request.GetRequestStream())
    {
        writer.Write(byteStream, 0, (int)request.ContentLength);
        writer.Flush();
    }

    HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
    string respStr = "";
    if (request.HaveResponse)
    {
        if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
        {
            StreamReader respReader = new StreamReader(resp.GetResponseStream());
            respStr = respReader.ReadToEnd(); // get the xml result in the string object  

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(respStr);
            Label1.Text = doc.InnerXml.ToString();


        }
    }  

1 个答案:

答案 0 :(得分:1)

您的代码应该没有太大区别,因为HTTP或HTTPS仅在传输级别而不是在应用程序级别上有所不同。 如果targetUri中使用的服务器证书在您的服务器上受信任,那么可能会出现问题的是。在这种情况下,无法验证HTTPS身份。