본문 바로가기

프로그램 경험/.Net

[C#] 윈폼에서 웹페이지로 데이터 전달

윈폼에서 웹페이지에 값을 전달 해야 할때가 있다.

그럴때 아래와 같이 사용한다.



using System;
using System.Text;
using System.Net;
using System.IO;

/**************************
 * 
 * C# APP 에서 웹페이지에 POST, GET으로 데이터 전송하기
 * 
    사용법)
   
    StringBuilder sbContent = new StringBuilder();
      
    sbContent.Append("body=");
    sbContent.Append(body);
    sbContent.Append("&subject=");
    sbContent.Append(subject);
    sbContent.Append("&to=");
    sbContent.Append(to);

    Classes.WebPageRequest wpr = new TestAllCodes.Classes.WebPageRequest("http://localhost/mailSend.aspx", "post");
    wpr.DataSend(sbContent.ToString());
 * 
 *************************/

namespace TestAllCodes.Classes
{
    class WebPageRequest
    {
        HttpWebRequest httpWebRequest;

        public WebPageRequest(string url, string method)
        {
            httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.Method = method.ToUpper();
            httpWebRequest.ContentType = @"application/x-www-form-urlencoded";
        }

        public void DataSend(string sendData)
        {
            byte[] sendDatas = Encoding.Default.GetBytes(sendData);

            httpWebRequest.ContentLength = sendDatas.Length;

            Stream stream = httpWebRequest.GetRequestStream();

            stream.Write(sendDatas, 0, sendDatas.Length);
            stream.Close();   
        }
    }
}