收送XML至其他網站

  • 2974
  • 0
  • 2013-09-25

收送XML至其他網站

    protected bool HttpWebRequest(string url, string strXML)
    {
        #region "收送XML至其他網站"
        try
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create(url);
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = strXML;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            //Response.Write(((HttpWebResponse)response).StatusDescription);  
            if (((HttpWebResponse)response).StatusDescription != "OK")
            {
             Response.Write("伺服器HttpWebResponse 回應錯誤!" +"\\r\\n" + ((HttpWebResponse)response).StatusDescription);
  
            }
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream, System.Text.Encoding.GetEncoding("BIG5"), false);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            //解析回傳的XML
            ParserXml(responseFromServer);
            // Display the content.
            //Response.Write(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
        catch (WebException e)
        {
            hdnErrMsg.Value ="WebException Message :" + e.Message + "\r\n";
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
                Response.Write(hdnErrMsg.Value.ToString() + "Status Code :" + ((HttpWebResponse)e.Response).StatusCode + "\r\n");
                Response.Write(hdnErrMsg.Value.ToString() + " Status Description :" + ((HttpWebResponse)e.Response).StatusDescription);
            }
            return false;
        }
        catch (Exception e)
        {
            Response.Write(e.Message);
            return false;
        }
        return true;
        #endregion
    }