본문 바로가기

.NET/C#

HttpRequest와 HttpResponse 사용법


HttpWebRequest myRequest =
                        (HttpWebRequest)WebRequest.Create("http://it-developer.tistory.com");
   string postData = string.Format("clipid={0}", 25060314);
   myRequest.Method = "POST";
   byte[] buffer = Encoding.UTF8.GetBytes(postData);


   // 컨텐츠 타입을 설정해 준다.
   myRequest.ContentType = "application/x-www-form-urlencoded";


   // 컨텐츠 길이를 설정해 준다.
   myRequest.ContentLength = buffer.Length;

    Stream newStream = myRequest.GetRequestStream();
    // 리퀘스트에 데이터를 삽입한다.
    newStream.Write(buffer, 0, buffer.Length);


    // 스트림을 닫는다.
    newStream.Close();
    // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse();


    // 리스폰스 객체를 얻어온다.
    Stream streamResponse = myHttpWebResponse.GetResponseStream();


    // StreamReader객체를 생성한다.
    StreamReader streamRead = new StreamReader(streamResponse);


    Char[] readBuffer = new Char[256];


    // 버퍼를 읽는다.
    int count = streamRead.Read(readBuffer, 0, 256);

    String resultData = String.Empty;
    while (count > 0)
    {
     // 스트링데이터를 만든다.
     resultData += new String(readBuffer, 0, count);  


     // 버퍼를 읽는다.
     count = streamRead.Read(readBuffer, 0, 256);
    }

    // 자원해제한다.
    streamRead.Close();
    streamResponse.Close();

    // 자원해제한다.
    myHttpWebResponse.Close();