자료/ASP.NET

HttpWebRequest 클래스를 이용한 POST 전송하기

네오블루 2011. 4. 27. 10:11
public static string postXMLHTTP(string sURL, string sParam, string requestType)
{
            string contentType = string.Empty;

            if (requestType.Equals("UTF-8"))
                contentType = "text/xml;charset=UTF-8";
            else
                postXMLHTTP(sURL, sParam);

            try
            {
                HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(sURL);
                HttpRequest.Method = "POST";
                string postData = sParam;

                System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                byte[] PostValue = Encoding.UTF8.GetBytes(postData);

                // Set the content type of the data being posted.
                //HttpRequest.ContentType = "application/x-www-form-urlencoded";
                HttpRequest.ContentType = "text/xml;charset=UTF-8";
                HttpRequest.ContentLength = PostValue.Length;

                Stream dataStream = HttpRequest.GetRequestStream();
                dataStream.Write(PostValue, 0, PostValue.Length);
                dataStream.Close();

                HttpWebResponse HttpResponse = (HttpWebResponse)HttpRequest.GetResponse();
                Stream respPostStream = HttpResponse.GetResponseStream();
                StreamReader respReader = new StreamReader(respPostStream, Encoding.UTF8);
                string strResponse = respReader.ReadToEnd();
                HttpResponse.Close();
                respReader.Close();

                return strResponse;
            }
            catch (Exception ex)
            { 
                return "ExceptionError : " + ex.Message;
            }
    }