2016년 11월 15일 화요일

[C#학원,닷넷학원,IT실무교육학원_탑크리에듀][강좌#8]HTTP와 닷넷(2)

WebClient 클래스 

데이터를 업로딩 하고 다운로딩 하는 작업은 일상적인 작업이나 기존에는 이러한 일을 하기 위해 서드파티 컴포넌트를 구압하거나 WinSock API를 사용해야 했습니다. 그러나 .NET Framework 에서는 기본적으로 이러한 클래스들을 제공 하죠... System.Net 네임스페이스에 있는 WebClient 클래스는 원격에서부터 데이터를 다운 받기 위한 3개의 메소드와 업로드 하기 위한 4개의 메소드를 제공하고 있습니다. 

생성자는 다음과 같습니다. 

WebClient client = new WebClient(); 

1.        DownloadData() 메소드 
DownloadData() 메소드의 파라미터는 URL 주소를 가리키는 문자열이 지정되며 지정된 주소로부터 획득한 바이트 배열을 되돌려 줍니다. 아래의 예제를 확인 하도록 하죠... 

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

class WebTest1 { 
        static void Main() { 
                WebClient client = new WebClient(); 
                byte[] urlData = client.DownloadData("http://localhost/oraclejava/main.html"); 

                string data = Encoding.Default.GetString(urlData); 
                Console.WriteLine(data); 
        } 


2.        DownloadFile() 메소드 : 파라미터로 URL 주소와 파일명을 가진다. 이때 지정된 리소스는 로컬드라이브의 파일로 다운 받을 수 있습니다. 아래의 예제를 확인 하죠~ 

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

class DownloadFile { 
        static void Main() { 
                WebClient client = new WebClient(); 
                string URL = "http://localhost/oraclejava/images/btn_login.gif"; 
                string fileName = @".\login.gif"; 
                
                client.DownloadFile(URL, fileName); 
        } 


3.        OpenRead() 메소드 

OpenRead() 메소드는 DownloadData() 메소드와 유사 합니다. 차이점이라면 대상 URL로부터 데이터를 읽을 수 있는 Stream객체를 돌려 준다는 점인데 이 메소드를 사용하면 Stream 객체의 Read()와 ReadBlock() 메소드를 이용하여 데이터의 일부분을 가져 올 수 있습니다. 

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

class OpenRead 

        static void Main() 
        { 
                byte[] bytes = new byte[409600]; 
                WebClient client = new WebClient(); 
                string URL = "http://localhost/oraclejava/main.html"; 
                Stream streamData = client.OpenRead(URL); 
                StreamReader sr = new StreamReader(streamData); 

                //파일을 생성 한다. 
                FileInfo file = new FileInfo (@".\main.html"); 
                StreamWriter sw = file.CreateText(); 
                
                sw.Write (sr.ReadToEnd()); 
                
                Console.WriteLine("writing file...");                
        } 


4.        OpenWrite() 메소드 

OpenWrite() 메소드를 이용하면 지정 URL로 데이터를 송신 할 수 있스빈다. 이 메소드는 POST 메소드나 다른 지원 메소드를 통해 데이터를 송신 하며 주소를 가리키는 문자열 파라미터와 사용하고자 하는 HTTP 메소드를 전달 받으며 지정된 URL로 보내기 위해 사용 할 스트림을 반환 합니다. 

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

class OpenWrite 

        static void Main() 
        {                
                string uriString = "http://localhost/oraclejava/multiboard/board/write_save.html"; 

                string name = "tatata"; 
                string email = "jclee@oraclejavanew.kr"; 
                string title = "board title"; 
                string password = "1111"; 
                string content = "boby content...."; 
                string board_code = "freeboard"; 

                string postData = "board_code=" + HttpUtility.UrlEncode(board_code) + "&" + 
                                                  "name=" + HttpUtility.UrlEncode(name) + "&" + 
                                  "email=" + HttpUtility.UrlEncode(email) + "&" + 
                                                  "title=" + HttpUtility.UrlEncode(title) + "&" + 
                                                  "password=" + HttpUtility.UrlEncode(password) + "&" + 
                                                  "content=" + HttpUtility.UrlEncode(content); 
                                        
                byte[] postArray = Encoding.Default.GetBytes(postData); 

                // Create a new WebClient instance. 
                WebClient myWebClient = new WebClient(); 
                myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 

                // postStream implicitly sets HTTP POST as the request method. 
                Console.WriteLine("Uploading to {0} ...",  uriString);                                                        
                Stream postStream = myWebClient.OpenWrite(uriString); 

                postStream.Write(postArray,0,postArray.Length); 

                // Close the stream and release resources. 
                postStream.Close(); 

                Console.WriteLine("\nSuccessfully posted the data."); 
        } 


5.        UploadData() 메소드 
인코딩을 수행 하지 않고 바이트 배열의 데이터를 서버로 송신 합니다. 이때 파라미터로 URL을 가지며 업로드 메소드(“POST”,”GET”)도 전달 가능 합니다. 

6.        UploadFile() 메소드 
로컬 디스크의 파일을 업로드 한다. 지정된 파일을 업로드 하며 대상 URL의 응답을 바이트 배열로 되돌려 받을 수 있습니다. 

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

class UploadFile 

        static void Main(string[] args) 
        { 
                string siteURL="http://localhost/test/HTTP.txt"; 
                string remoteResponse;        

                // Create a new WebClient instance. 
                WebClient client = new WebClient(); 

                NetworkCredential cred = new NetworkCredential("Administrator", ""); 

                string fileName = @"..\..\UploadFile.cs"; 
                Console.WriteLine("Uploading {0} to {1} ...", fileName, siteURL); 

                // File Uploaded using PUT method 
                byte[] responseArray = client.UploadFile (siteURL, "PUT", fileName); 

                //Response from the Target URL 
                remoteResponse = Encoding.ASCII.GetString(responseArray); 
                Console.WriteLine(remoteResponse); 
        } 

댓글 없음:

댓글 쓰기